import { useState, useEffect } from "react";
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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Loader2, FolderUp, HardDrive } from "lucide-react";
import { supabase } from "@/integrations/supabase/client";
import { useToast } from "@/hooks/use-toast";
import { useDocumentSummary } from "@/hooks/useDocumentSummary";
import { buildSecureStorageKey } from "@/lib/secureStorageNaming";
import { useGoogleDrive } from "@/hooks/useGoogleDrive";
import GoogleDriveFolderPickerDialog from "@/components/documents/GoogleDriveFolderPickerDialog";

const defaultFolders = [
  "Uncategorized", "Bank Statements", "Collections", "Financials", "Insurance",
  "Litigation", "Management Reports", "Meetings", "New Owner Files",
  "Owner Correspondence", "Reports",
];

/**
 * SaveToDocumentsDialog
 * 
 * Props:
 * - open / onOpenChange
 * - generatePdfBlob: async () => Blob  — called to produce the PDF
 * - defaultTitle: string
 * - associationId: string | null       — pre-selected association
 * - associations: { id, name }[]       — if not provided, will fetch
 */
export default function SaveToDocumentsDialog({
  open,
  onOpenChange,
  generatePdfBlob,
  defaultTitle = "",
  associationId = null,
  associations: externalAssociations,
  residentFileMode = false,
  unitId = "",
  unitNumber = "",
  unitAddress = "",
}) {
  const { toast } = useToast();
  const { generateSummary } = useDocumentSummary();
  const drive = useGoogleDrive();
  const [saving, setSaving] = useState(false);
  const [title, setTitle] = useState("");
  const [folder, setFolder] = useState("Owner Correspondence");
  const [selectedAssociation, setSelectedAssociation] = useState("");
  const [associations, setAssociations] = useState([]);
  const [customFolders, setCustomFolders] = useState([]);
  const [saveToDrive, setSaveToDrive] = useState(false);
  const [driveFolder, setDriveFolder] = useState(null);
  const [drivePickerOpen, setDrivePickerOpen] = useState(false);
  const [resolvedAddress, setResolvedAddress] = useState("");

  // Auto-recognize the unit's street address. Prefer an address explicitly
  // passed in; otherwise look it up from the units table by unit_id so the
  // Resident Files folder is named by address instead of an opaque UUID.
  useEffect(() => {
    if (!residentFileMode) { setResolvedAddress(""); return; }
    if (unitAddress) { setResolvedAddress(unitAddress); return; }
    if (!unitId) { setResolvedAddress(""); return; }
    let cancelled = false;
    supabase.from("units").select("address, unit_number").eq("id", unitId).maybeSingle()
      .then(({ data }) => { if (!cancelled) setResolvedAddress(data?.address || data?.unit_number || ""); });
    return () => { cancelled = true; };
  }, [residentFileMode, unitId, unitAddress]);

  // Folder name uses the address when available, then unit number, then UUID.
  const residentFolderName = resolvedAddress || unitAddress || unitNumber || unitId;
  const residentFolder = residentFolderName ? `Resident Files/${residentFolderName}` : "Resident Files";

  useEffect(() => {
    if (open) {
      setTitle(defaultTitle);
      setSelectedAssociation(associationId || "");
      setSaveToDrive(false);
      setDriveFolder(null);
      if (residentFileMode) setFolder(residentFolder);
      // Load custom folders from localStorage
      try {
        const stored = localStorage.getItem("doc_custom_folders");
        if (stored) setCustomFolders(JSON.parse(stored));
      } catch { setCustomFolders([]); }
    }
  }, [open, defaultTitle, associationId, residentFileMode, residentFolder]);

  useEffect(() => {
    if (externalAssociations) {
      setAssociations(externalAssociations);
    } else if (open) {
      supabase.from("associations").select("id, name").eq("status", "active").order("name")
        .then(({ data }) => setAssociations(data || []));
    }
  }, [open, externalAssociations]);

  const allFolders = [...new Set([...defaultFolders, ...customFolders])].sort();

  const handleSave = async () => {
    if (!title.trim()) {
      toast({ title: "Title required", description: "Please enter a document title.", variant: "destructive" });
      return;
    }
    if (!selectedAssociation) {
      toast({ title: "Association required", description: "Please select an association.", variant: "destructive" });
      return;
    }

    setSaving(true);
    try {
      // Generate PDF blob
      const blob = await generatePdfBlob();
      if (!blob) throw new Error("Failed to generate PDF");

      // Display name preserved on the documents row; storage key is randomized
      // so the public URL doesn't expose the document's real name.
      const displayFileName = `${title.replace(/[^a-zA-Z0-9._ -]+/g, "_").trim()}.pdf`;
      const filePath = buildSecureStorageKey(
        "doc.pdf",
        `documents/${selectedAssociation}`,
      );

      const { error: uploadError } = await supabase.storage
        .from("files")
        .upload(filePath, blob, { contentType: "application/pdf" });
      if (uploadError) throw uploadError;

      const { data: urlData } = supabase.storage.from("files").getPublicUrl(filePath);

      // Create document record
      const { data: { user } } = await supabase.auth.getUser();
      const { data: insertData, error: insertError } = await supabase.from("documents").insert({
        title: title.trim(),
        association_id: selectedAssociation,
        category: folder === "Uncategorized" ? "general" : folder,
        file_name: displayFileName,
        file_url: urlData.publicUrl,
        file_size: blob.size,
        uploaded_by: user?.id || null,
      }).select("id").single();
      if (insertError) throw insertError;

      if (saveToDrive) {
        if (!drive.isConnected) throw new Error("Connect Google Drive before saving there.");
        const driveFile = new File([blob], displayFileName, { type: "application/pdf" });
        const result = await drive.uploadFile(driveFile, driveFolder?.id || undefined);
        if (!result.success) throw new Error("Document saved locally, but Google Drive upload failed.");
      }

      // Trigger AI summary in background for management reports
      const folderLower = (folder || "").toLowerCase();
      if (folderLower.includes("management") || folderLower.includes("report")) {
        generateSummary(insertData.id, urlData.publicUrl, title.trim());
      }

      toast({ title: "Saved to Documents", description: saveToDrive ? `"${title}" saved to Documents and Google Drive.` : `"${title}" saved to ${folder}.` });
      onOpenChange(false);
    } catch (err) {
      console.error("Error saving to documents:", err);
      toast({ title: "Error", description: err.message || "Failed to save document.", variant: "destructive" });
    } finally {
      setSaving(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[440px]">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <FolderUp className="h-5 w-5 text-primary" />
            {residentFileMode ? "Save to Resident File" : "Save to Documents"}
          </DialogTitle>
          <DialogDescription>
            {residentFileMode
              ? `This document will be saved under "Resident Files / ${residentFolderName || "(no unit)"}" inside the selected association.`
              : "Save this file to the Documents library for easy access."}
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-4 py-2">
          <div className="space-y-1.5">
            <Label className="text-xs font-medium">Document Title</Label>
            <Input value={title} onChange={(e) => setTitle(e.target.value)} placeholder="e.g. Late Notice - Unit 101" />
          </div>

          <div className="space-y-1.5">
            <Label className="text-xs font-medium">Association</Label>
            <Select value={selectedAssociation} onValueChange={setSelectedAssociation}>
              <SelectTrigger>
                <SelectValue placeholder="Select Association" />
              </SelectTrigger>
              <SelectContent>
                {associations.map((a) => (
                  <SelectItem key={a.id} value={a.id}>{a.name}</SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          <div className="space-y-1.5">
            <Label className="text-xs font-medium">Folder</Label>
            {residentFileMode ? (
              <Input value={residentFolder} disabled className="bg-muted text-muted-foreground" />
            ) : (
              <Select value={folder} onValueChange={setFolder}>
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {allFolders.map((f) => (
                    <SelectItem key={f} value={f}>{f}</SelectItem>
                  ))}
                </SelectContent>
              </Select>
            )}
          </div>

          <div className="rounded-md border border-border p-3 space-y-2">
            <div className="flex items-center justify-between gap-3">
              <div className="min-w-0">
                <Label className="text-xs font-medium flex items-center gap-2">
                  <HardDrive className="h-4 w-4 text-primary" /> Save to Google Drive
                </Label>
                <p className="text-xs text-muted-foreground truncate">
                  {driveFolder?.name || "Choose a Drive folder for this PDF."}
                </p>
              </div>
              <Button type="button" variant="outline" size="sm" onClick={() => { setSaveToDrive(true); setDrivePickerOpen(true); }} disabled={!drive.isConnected || saving}>
                Choose
              </Button>
            </div>
            {!drive.isConnected && <p className="text-xs text-muted-foreground">Connect Google Drive from Documents before saving files there.</p>}
            {driveFolder && (
              <Button type="button" variant="ghost" size="sm" className="h-7 px-2" onClick={() => { setSaveToDrive(false); setDriveFolder(null); }}>
                Remove Google Drive save
              </Button>
            )}
          </div>
        </div>

        <DialogFooter>
          <Button variant="ghost" onClick={() => onOpenChange(false)} disabled={saving}>Cancel</Button>
          <Button onClick={handleSave} disabled={saving}>
            {saving && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
            {residentFileMode ? "Save to Resident File" : "Save to Documents"}
          </Button>
        </DialogFooter>
      </DialogContent>

      <GoogleDriveFolderPickerDialog
        open={drivePickerOpen}
        onOpenChange={setDrivePickerOpen}
        driveFiles={drive.driveFiles}
        browsing={drive.browsing}
        browseFiles={drive.browseFiles}
        listSharedDrives={drive.listSharedDrives}
        onSelect={(selected) => { setDriveFolder(selected); setSaveToDrive(true); }}
      />
    </Dialog>
  );
}
