import { useState, useEffect, useCallback } from "react";
import { FolderOpen, FilePlus, FolderPlus, RefreshCw, Search } from "lucide-react";
import { invoke } from "@tauri-apps/api/core";
import { open } from "@tauri-apps/plugin-dialog";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { FileTreeNode } from "@/components/FileTreeNode";
import { useStore, actions } from "@/lib/store";

interface DirEntry {
  name: string;
  path: string;
  is_dir: boolean;
}

export function FileTree() {
  const { workspacePath, fileTreeFilter } = useStore();
  const [entries, setEntries] = useState<DirEntry[]>([]);

  const loadEntries = useCallback(async () => {
    if (!workspacePath) return;
    try {
      const result = await invoke<DirEntry[]>("read_directory", { path: workspacePath });
      setEntries(result);
    } catch (err) {
      console.error("Failed to read workspace:", err);
    }
  }, [workspacePath]);

  useEffect(() => {
    loadEntries();
  }, [loadEntries]);

  const handleOpenFolder = useCallback(async () => {
    const selected = await open({ directory: true, multiple: false });
    if (selected) {
      actions.setWorkspace(selected as string);
    }
  }, []);

  const handleNewFile = useCallback(async () => {
    if (!workspacePath) return;
    const name = prompt("File name:");
    if (!name) return;
    try {
      await invoke("create_file", { path: workspacePath + "/" + name });
      loadEntries();
    } catch (err) {
      console.error("Failed to create file:", err);
    }
  }, [workspacePath, loadEntries]);

  const handleNewFolder = useCallback(async () => {
    if (!workspacePath) return;
    const name = prompt("Folder name:");
    if (!name) return;
    try {
      await invoke("create_directory", { path: workspacePath + "/" + name });
      loadEntries();
    } catch (err) {
      console.error("Failed to create folder:", err);
    }
  }, [workspacePath, loadEntries]);

  const folderName = workspacePath?.split("/").pop() ?? workspacePath?.split("\\").pop();

  if (!workspacePath) {
    return (
      <div className="flex h-full flex-col items-center justify-center gap-3 px-4">
        <p className="text-sm text-muted-foreground text-center">No folder open</p>
        <Button variant="secondary" size="sm" onClick={handleOpenFolder} className="gap-1.5">
          <FolderOpen className="h-4 w-4" />
          Open Folder
        </Button>
      </div>
    );
  }

  return (
    <div className="flex h-full flex-col">
      <div className="flex h-8 items-center justify-between px-3 text-xs font-semibold uppercase tracking-wider text-muted-foreground shrink-0">
        <span className="truncate">{folderName}</span>
        <div className="flex items-center gap-0.5">
          <Tooltip>
            <TooltipTrigger asChild>
              <Button variant="ghost" size="icon" className="h-5 w-5" onClick={handleNewFile}>
                <FilePlus className="h-3.5 w-3.5" />
              </Button>
            </TooltipTrigger>
            <TooltipContent>New File</TooltipContent>
          </Tooltip>
          <Tooltip>
            <TooltipTrigger asChild>
              <Button variant="ghost" size="icon" className="h-5 w-5" onClick={handleNewFolder}>
                <FolderPlus className="h-3.5 w-3.5" />
              </Button>
            </TooltipTrigger>
            <TooltipContent>New Folder</TooltipContent>
          </Tooltip>
          <Tooltip>
            <TooltipTrigger asChild>
              <Button variant="ghost" size="icon" className="h-5 w-5" onClick={loadEntries}>
                <RefreshCw className="h-3.5 w-3.5" />
              </Button>
            </TooltipTrigger>
            <TooltipContent>Refresh</TooltipContent>
          </Tooltip>
        </div>
      </div>
      <div className="px-2 pb-1 shrink-0">
        <div className="relative">
          <Search className="absolute left-2 top-1/2 -translate-y-1/2 h-3 w-3 text-muted-foreground" />
          <Input
            placeholder="Filter files..."
            value={fileTreeFilter}
            onChange={(e) => actions.setFileTreeFilter(e.target.value)}
            className="h-6 pl-6 text-xs"
          />
        </div>
      </div>
      <ScrollArea className="flex-1">
        <div className="pb-4">
          {entries.map((entry) => (
            <FileTreeNode
              key={entry.path}
              entry={entry}
              depth={0}
              filter={fileTreeFilter}
              onRefresh={loadEntries}
            />
          ))}
        </div>
      </ScrollArea>
    </div>
  );
}
