import { useState, useEffect } from "react";
import { supabase } from "@/integrations/supabase/client";
import { useToast } from "@/hooks/use-toast";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
import { Globe, Copy, RefreshCw, Lock, Shield } from "lucide-react";

function generateCode(length = 8): string {
  const chars = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
  let code = "";
  for (let i = 0; i < length; i++) code += chars[Math.floor(Math.random() * chars.length)];
  return code;
}

interface ShareDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  shareType: "folder" | "document";
  folderName?: string;
  documentId?: string;
  itemName: string;
}

export default function ShareDialog({ open, onOpenChange, shareType, folderName, documentId, itemName }: ShareDialogProps) {
  const { toast } = useToast();
  const [link, setLink] = useState<any>(null);
  const [loading, setLoading] = useState(false);
  const [saving, setSaving] = useState(false);

  useEffect(() => {
    if (open) fetchExisting();
  }, [open, shareType, folderName, documentId]);

  const fetchExisting = async () => {
    setLoading(true);
    let query = supabase.from("shared_links").select("*");
    if (shareType === "folder") query = query.eq("share_type", "folder").eq("folder_name", folderName || "");
    else query = query.eq("share_type", "document").eq("document_id", documentId || "");
    const { data } = await query.limit(1).single();
    setLink(data || null);
    setLoading(false);
  };

  const baseUrl = window.location.origin;

  const handleTogglePublic = async (enabled: boolean) => {
    setSaving(true);
    if (!link) {
      const { data: { user } } = await supabase.auth.getUser();
      const newCode = generateCode();
      const payload: any = {
        share_type: shareType,
        is_public: enabled,
        access_code: newCode,
        created_by: user?.id,
      };
      if (shareType === "folder") payload.folder_name = folderName;
      else payload.document_id = documentId;
      const { data, error } = await supabase.from("shared_links").insert(payload).select().single();
      if (error) toast({ title: "Error", description: error.message, variant: "destructive" });
      else setLink(data);
    } else {
      const { data, error } = await supabase.from("shared_links").update({ is_public: enabled }).eq("id", link.id).select().single();
      if (error) toast({ title: "Error", description: error.message, variant: "destructive" });
      else setLink(data);
    }
    setSaving(false);
  };

  const regenerateLink = async () => {
    if (!link) return;
    const newToken = Array.from(crypto.getRandomValues(new Uint8Array(16))).map(b => b.toString(16).padStart(2, "0")).join("");
    const { data, error } = await supabase.from("shared_links").update({ share_token: newToken }).eq("id", link.id).select().single();
    if (error) toast({ title: "Error", description: error.message, variant: "destructive" });
    else { setLink(data); toast({ title: "Link regenerated" }); }
  };

  const regenerateCode = async () => {
    if (!link) return;
    const newCode = generateCode();
    const { data, error } = await supabase.from("shared_links").update({ access_code: newCode }).eq("id", link.id).select().single();
    if (error) toast({ title: "Error", description: error.message, variant: "destructive" });
    else { setLink(data); toast({ title: "Access code regenerated" }); }
  };

  const copyToClipboard = (text: string, label: string) => {
    navigator.clipboard.writeText(text);
    toast({ title: "Copied", description: `${label} copied to clipboard.` });
  };

  const shareUrl = link ? `${baseUrl}/shared/${link.share_token}` : "";

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-md">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <Globe className="h-5 w-5 text-primary" />
            Share {shareType === "folder" ? "Folder" : "Document"}: {itemName}
          </DialogTitle>
          <DialogDescription>Generate a secure link for external users.</DialogDescription>
        </DialogHeader>

        {loading ? (
          <div className="py-8 text-center text-muted-foreground text-sm">Loading...</div>
        ) : (
          <div className="space-y-5">
            {/* Public Sharing Toggle */}
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-semibold">Public Sharing</p>
                <p className="text-xs text-muted-foreground">
                  {link?.is_public ? "Enabled - Folder is accessible with link & code" : "Disabled - Not shared"}
                </p>
              </div>
              <Switch
                checked={link?.is_public ?? false}
                onCheckedChange={handleTogglePublic}
                disabled={saving}
              />
            </div>

            {link?.is_public && (
              <>
                {/* Share Link */}
                <div className="space-y-2">
                  <Label className="text-xs font-bold uppercase tracking-wider text-muted-foreground">1. Share Link</Label>
                  <div className="flex gap-2">
                    <Input readOnly value={shareUrl} className="text-xs font-mono bg-muted" />
                    <Button variant="outline" size="icon" className="shrink-0" onClick={() => copyToClipboard(shareUrl, "Share link")}>
                      <Copy className="h-4 w-4" />
                    </Button>
                  </div>
                  <button onClick={regenerateLink} className="text-xs text-primary hover:underline flex items-center gap-1">
                    <RefreshCw className="h-3 w-3" /> Regenerate Link
                  </button>
                </div>

                {/* Access Code */}
                <div className="space-y-2">
                  <div className="flex items-center justify-between">
                    <Label className="text-xs font-bold uppercase tracking-wider text-muted-foreground">2. Access Code</Label>
                    <button onClick={regenerateCode} className="text-xs text-primary hover:underline flex items-center gap-1">
                      <RefreshCw className="h-3 w-3" /> New Code
                    </button>
                  </div>
                  <div className="rounded-lg border-2 border-amber-400 bg-amber-50 dark:bg-amber-950/20 p-4">
                    <div className="flex items-center gap-2 mb-2">
                      <Shield className="h-4 w-4 text-amber-600" />
                      <span className="text-xs font-bold text-amber-700 dark:text-amber-400 uppercase">Authentication Required</span>
                    </div>
                    <div className="flex items-center gap-2">
                      <Input
                        readOnly
                        value={link?.access_code || ""}
                        className="text-center text-lg font-mono font-bold tracking-[0.3em] bg-background border-2"
                      />
                      <Button variant="outline" size="icon" className="shrink-0" onClick={() => copyToClipboard(link?.access_code || "", "Access code")}>
                        <Copy className="h-4 w-4" />
                      </Button>
                    </div>
                    <p className="text-xs text-amber-600 dark:text-amber-400 mt-2 text-center">
                      External users must enter this code to view files.
                    </p>
                  </div>
                </div>
              </>
            )}
          </div>
        )}

        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)}>Cancel</Button>
          <Button onClick={() => onOpenChange(false)}>Save Settings</Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
