import { useState, useEffect } from "react";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Folder, File, ArrowLeft, Loader2, ChevronRight } from "lucide-react";
import { Badge } from "@/components/ui/badge";

interface DriveFile {
  id: string;
  name: string;
  mimeType: string;
  iconLink?: string;
  webViewLink?: string;
  size?: string;
  modifiedTime?: string;
}

interface GoogleDrivePickerDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  driveFiles: DriveFile[];
  browsing: boolean;
  browseFiles: (folderId?: string) => Promise<void>;
  listSharedDrives: () => Promise<void>;
  onShare: (files: DriveFile[], visibility: string[], associationIds: string[]) => Promise<void>;
  associations: { id: string; name: string }[];
}

export default function GoogleDrivePickerDialog({
  open,
  onOpenChange,
  driveFiles,
  browsing,
  browseFiles,
  listSharedDrives,
  onShare,
  associations,
}: GoogleDrivePickerDialogProps) {
  const [selectedFiles, setSelectedFiles] = useState<DriveFile[]>([]);
  const [folderStack, setFolderStack] = useState<{ id: string; name: string }[]>([]);
  const [visibility, setVisibility] = useState<string[]>(["admin"]);
  const [selectedAssociationIds, setSelectedAssociationIds] = useState<string[]>([]);
  const [sharing, setSharing] = useState(false);
  const [step, setStep] = useState<"browse" | "configure">("browse");

  useEffect(() => {
    if (open) {
      listSharedDrives();
      setSelectedFiles([]);
      setFolderStack([]);
      setVisibility(["admin"]);
      setSelectedAssociationIds([]);
      setStep("browse");
    }
  }, [open]);

  const navigateToFolder = (file: DriveFile) => {
    setFolderStack(prev => [...prev, { id: file.id, name: file.name }]);
    browseFiles(file.id);
  };

  const navigateBack = () => {
    const newStack = [...folderStack];
    newStack.pop();
    setFolderStack(newStack);
    if (newStack.length === 0) {
      listSharedDrives();
    } else {
      browseFiles(newStack[newStack.length - 1].id);
    }
  };

  const toggleFile = (file: DriveFile) => {
    setSelectedFiles(prev => {
      const exists = prev.find(f => f.id === file.id);
      if (exists) return prev.filter(f => f.id !== file.id);
      return [...prev, file];
    });
  };

  const isFolder = (f: DriveFile) => f.mimeType === "application/vnd.google-apps.folder";

  const toggleVisibility = (role: string) => {
    setVisibility(prev =>
      prev.includes(role) ? prev.filter(r => r !== role) : [...prev, role]
    );
  };

  const toggleAssociation = (id: string) => {
    setSelectedAssociationIds(prev =>
      prev.includes(id) ? prev.filter(a => a !== id) : [...prev, id]
    );
  };

  const handleShare = async () => {
    if (selectedFiles.length === 0) return;
    setSharing(true);
    await onShare(selectedFiles, visibility, selectedAssociationIds);
    setSharing(false);
    onOpenChange(false);
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-2xl max-h-[80vh] flex flex-col">
        <DialogHeader>
          <DialogTitle>
            {step === "browse" ? "Select Files from Google Drive" : "Configure Sharing"}
          </DialogTitle>
          <DialogDescription>
            {step === "browse"
              ? "Browse your Drive and select files or folders to share."
              : "Choose who can see these files."}
          </DialogDescription>
        </DialogHeader>

        {step === "browse" ? (
          <>
            {/* Breadcrumb */}
            <div className="flex items-center gap-1 text-sm text-muted-foreground mb-2">
              <button
                onClick={() => { setFolderStack([]); listSharedDrives(); }}
                className="hover:text-foreground font-medium"
              >
                Shared Drives
              </button>
              {folderStack.map((f, i) => (
                <span key={f.id} className="flex items-center gap-1">
                  <ChevronRight className="h-3 w-3" />
                  <button
                    onClick={() => {
                      const newStack = folderStack.slice(0, i + 1);
                      setFolderStack(newStack);
                      browseFiles(f.id);
                    }}
                    className="hover:text-foreground"
                  >
                    {f.name}
                  </button>
                </span>
              ))}
            </div>

            {/* File list */}
            <div className="flex-1 overflow-y-auto border rounded-md min-h-[300px] max-h-[400px]">
              {browsing ? (
                <div className="flex items-center justify-center py-12">
                  <Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
                </div>
              ) : driveFiles.length === 0 ? (
                <div className="flex flex-col items-center justify-center py-12 text-muted-foreground">
                  <Folder className="h-8 w-8 mb-2 opacity-40" />
                  <p className="text-sm">This folder is empty</p>
                </div>
              ) : (
                <div className="divide-y">
                  {driveFiles.map(file => {
                    const folder = isFolder(file);
                    const selected = selectedFiles.some(f => f.id === file.id);

                    return (
                      <div
                        key={file.id}
                        className={`flex items-center gap-3 px-4 py-2.5 hover:bg-muted/50 cursor-pointer transition-colors ${
                          selected ? "bg-primary/5" : ""
                        }`}
                      >
                        <Checkbox
                          checked={selected}
                          onCheckedChange={() => toggleFile(file)}
                        />
                        <div
                          className="flex items-center gap-3 flex-1 min-w-0"
                          onClick={() => folder ? navigateToFolder(file) : toggleFile(file)}
                        >
                          {file.iconLink ? (
                            <img src={file.iconLink} alt="" className="h-5 w-5 shrink-0" />
                          ) : folder ? (
                            <Folder className="h-5 w-5 text-primary shrink-0" />
                          ) : (
                            <File className="h-5 w-5 text-muted-foreground shrink-0" />
                          )}
                          <span className="text-sm truncate">{file.name}</span>
                          {folder && <ChevronRight className="h-4 w-4 text-muted-foreground ml-auto shrink-0" />}
                        </div>
                      </div>
                    );
                  })}
                </div>
              )}
            </div>

            {/* Selection summary */}
            {selectedFiles.length > 0 && (
              <div className="text-sm text-muted-foreground">
                {selectedFiles.length} item{selectedFiles.length !== 1 ? "s" : ""} selected
              </div>
            )}

            <DialogFooter>
              <Button variant="outline" onClick={() => onOpenChange(false)}>Cancel</Button>
              <Button
                onClick={() => setStep("configure")}
                disabled={selectedFiles.length === 0}
              >
                Next: Configure Sharing
              </Button>
            </DialogFooter>
          </>
        ) : (
          <>
            {/* Selected files summary */}
            <div className="space-y-3">
              <div>
                <Label className="text-xs font-bold uppercase text-muted-foreground">Selected Files</Label>
                <div className="mt-1 flex flex-wrap gap-1.5">
                  {selectedFiles.map(f => (
                    <Badge key={f.id} variant="secondary" className="text-xs">
                      {isFolder(f) ? "📁 " : "📄 "}{f.name}
                    </Badge>
                  ))}
                </div>
              </div>

              {/* Visibility */}
              <div>
                <Label className="text-xs font-bold uppercase text-muted-foreground">Who can see these files?</Label>
                <div className="mt-2 space-y-2">
                  {[
                    { value: "admin", label: "Admin / Staff" },
                    { value: "board_member", label: "Board Members" },
                    { value: "homeowner", label: "Homeowners" },
                  ].map(role => (
                    <label key={role.value} className="flex items-center gap-2 cursor-pointer">
                      <Checkbox
                        checked={visibility.includes(role.value)}
                        onCheckedChange={() => toggleVisibility(role.value)}
                        disabled={role.value === "admin"}
                      />
                      <span className="text-sm">{role.label}</span>
                      {role.value === "admin" && (
                        <span className="text-xs text-muted-foreground">(always visible)</span>
                      )}
                    </label>
                  ))}
                </div>
              </div>

              {/* Association filter */}
              {(visibility.includes("board_member") || visibility.includes("homeowner")) && (
                <div>
                  <Label className="text-xs font-bold uppercase text-muted-foreground">
                    Share with which associations?
                  </Label>
                  <p className="text-xs text-muted-foreground mb-2">
                    Only users belonging to selected associations will see these files.
                  </p>
                  <div className="mt-1 space-y-1.5 max-h-[200px] overflow-y-auto border rounded-md p-2">
                    {associations.map(a => (
                      <label key={a.id} className="flex items-center gap-2 cursor-pointer py-1 px-1 rounded hover:bg-muted/50">
                        <Checkbox
                          checked={selectedAssociationIds.includes(a.id)}
                          onCheckedChange={() => toggleAssociation(a.id)}
                        />
                        <span className="text-sm">{a.name}</span>
                      </label>
                    ))}
                  </div>
                </div>
              )}
            </div>

            <DialogFooter>
              <Button variant="outline" onClick={() => setStep("browse")}>
                <ArrowLeft className="h-4 w-4 mr-1" /> Back
              </Button>
              <Button
                onClick={handleShare}
                disabled={sharing || (
                  (visibility.includes("board_member") || visibility.includes("homeowner"))
                  && selectedAssociationIds.length === 0
                )}
              >
                {sharing ? <Loader2 className="h-4 w-4 animate-spin mr-1" /> : null}
                {sharing ? "Sharing..." : `Share ${selectedFiles.length} Item${selectedFiles.length !== 1 ? "s" : ""}`}
              </Button>
            </DialogFooter>
          </>
        )}
      </DialogContent>
    </Dialog>
  );
}
