import { useEffect, useState } from "react";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Folder, ArrowLeft, Loader2, ChevronRight, HardDrive } from "lucide-react";

interface DriveFile {
  id: string;
  name: string;
  mimeType: string;
}

interface Props {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  driveFiles: DriveFile[];
  browsing: boolean;
  browseFiles: (folderId?: string) => Promise<void>;
  listSharedDrives: () => Promise<void>;
  onSelect: (folder: { id: string | null; name: string }) => void;
}

export default function GoogleDriveFolderPickerDialog({
  open,
  onOpenChange,
  driveFiles,
  browsing,
  browseFiles,
  listSharedDrives,
  onSelect,
}: Props) {
  const [folderStack, setFolderStack] = useState<{ id: string; name: string }[]>([]);

  useEffect(() => {
    if (open) {
      setFolderStack([]);
      listSharedDrives();
    }
  }, [open, listSharedDrives]);

  const currentFolder = folderStack[folderStack.length - 1] || null;
  const folders = driveFiles.filter((file) => file.mimeType === "application/vnd.google-apps.folder");

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

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

  const handleUseFolder = () => {
    onSelect(currentFolder ? { id: currentFolder.id, name: currentFolder.name } : { id: null, name: "My Drive" });
    onOpenChange(false);
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-2xl max-h-[80vh] flex flex-col">
        <DialogHeader>
          <DialogTitle>Choose Google Drive Folder</DialogTitle>
          <DialogDescription>Select where this file should be saved.</DialogDescription>
        </DialogHeader>

        <div className="flex items-center gap-1 text-sm text-muted-foreground">
          <button onClick={() => { setFolderStack([]); listSharedDrives(); }} className="hover:text-foreground font-medium">
            Shared Drives
          </button>
          {folderStack.map((folder, index) => (
            <span key={folder.id} className="flex items-center gap-1 min-w-0">
              <ChevronRight className="h-3 w-3 shrink-0" />
              <button
                onClick={() => {
                  const nextStack = folderStack.slice(0, index + 1);
                  setFolderStack(nextStack);
                  browseFiles(folder.id);
                }}
                className="hover:text-foreground truncate"
              >
                {folder.name}
              </button>
            </span>
          ))}
        </div>

        <div className="flex-1 overflow-y-auto border rounded-md min-h-[300px] max-h-[420px]">
          {browsing ? (
            <div className="flex items-center justify-center py-12">
              <Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
            </div>
          ) : folders.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">No folders here</p>
            </div>
          ) : (
            <div className="divide-y">
              {folders.map((folder) => (
                <button
                  key={folder.id}
                  onClick={() => navigateToFolder(folder)}
                  className="w-full flex items-center gap-3 px-4 py-2.5 hover:bg-muted/50 text-left transition-colors"
                >
                  <Folder className="h-5 w-5 text-primary shrink-0" />
                  <span className="text-sm truncate flex-1">{folder.name}</span>
                  <ChevronRight className="h-4 w-4 text-muted-foreground shrink-0" />
                </button>
              ))}
            </div>
          )}
        </div>

        <DialogFooter className="gap-2">
          {folderStack.length > 0 && (
            <Button type="button" variant="outline" onClick={navigateBack}>
              <ArrowLeft className="h-4 w-4 mr-2" /> Back
            </Button>
          )}
          <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>Cancel</Button>
          <Button type="button" onClick={handleUseFolder}>
            <HardDrive className="h-4 w-4 mr-2" /> Save here
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}