"use client";

import { useState, useCallback } from "react";
import { FolderOpen, FolderClosed, ChevronRight, ChevronDown } from "lucide-react";
import { cn } from "@/lib/utils";
import { fetchFileTree, type FileTreeNode } from "@/lib/api/workspace";
import { getFileCategoryIcon } from "@/lib/workspace-file-types";

type FileTreeProps = {
  workspaceId: string;
  nodes: FileTreeNode[];
  onSelectFile: (path: string) => void;
  selectedPath?: string;
};

type TreeNodeProps = {
  workspaceId: string;
  node: FileTreeNode;
  depth: number;
  onSelectFile: (path: string) => void;
  selectedPath?: string;
};

function TreeNode({ workspaceId, node, depth, onSelectFile, selectedPath }: TreeNodeProps) {
  const [expanded, setExpanded] = useState(depth === 0);
  const [children, setChildren] = useState<FileTreeNode[] | null>(node.children ?? null);
  const [loading, setLoading] = useState(false);

  const isDir = node.type === "dir";
  const isSelected = selectedPath === node.path;

  const handleToggle = useCallback(async () => {
    if (!isDir) {
      onSelectFile(node.path);
      return;
    }

    if (!expanded && children === null) {
      // Lazy load children
      setLoading(true);
      try {
        const fetched = await fetchFileTree(workspaceId, node.path, 1);
        setChildren(fetched);
      } catch (err) {
        console.error("Failed to load directory:", err);
        setChildren([]);
      } finally {
        setLoading(false);
      }
    }
    setExpanded(!expanded);
  }, [isDir, expanded, children, workspaceId, node.path, onSelectFile]);

  return (
    <div>
      <div
        className={cn(
          "flex items-center gap-1.5 px-2 py-1 cursor-pointer transition-colors text-sm hover:bg-foreground/5 rounded-md",
          isSelected && "bg-primary/10 text-primary"
        )}
        style={{ paddingLeft: `${depth * 16 + 8}px` }}
        onClick={handleToggle}
      >
        {isDir ? (
          <>
            {loading ? (
              <div className="w-3.5 h-3.5 shrink-0 animate-spin rounded-full border border-primary/30 border-t-primary" />
            ) : expanded ? (
              <ChevronDown className="w-3.5 h-3.5 shrink-0 text-muted-foreground/60" />
            ) : (
              <ChevronRight className="w-3.5 h-3.5 shrink-0 text-muted-foreground/60" />
            )}
            {expanded ? (
              <FolderOpen className="w-4 h-4 shrink-0 text-primary/70" />
            ) : (
              <FolderClosed className="w-4 h-4 shrink-0 text-primary/50" />
            )}
          </>
        ) : (
          (() => {
            const FileIcon = getFileCategoryIcon(node.name);
            return (
              <>
                <span className="w-3.5 shrink-0" />
                <FileIcon className="w-4 h-4 shrink-0 text-muted-foreground/50" />
              </>
            );
          })()
        )}
        <span className={cn(
          "truncate text-xs font-mono",
          isDir ? "font-bold text-foreground/80" : "text-foreground/60"
        )}>
          {node.name}
        </span>
      </div>

      {isDir && expanded && children && (
        <div>
          {children.map((child) => (
            <TreeNode
              key={child.path}
              workspaceId={workspaceId}
              node={child}
              depth={depth + 1}
              onSelectFile={onSelectFile}
              selectedPath={selectedPath}
            />
          ))}
        </div>
      )}
    </div>
  );
}

export function FileTree({ workspaceId, nodes, onSelectFile, selectedPath }: FileTreeProps) {
  return (
    <div className="py-2">
      {nodes.map((node) => (
        <TreeNode
          key={node.path}
          workspaceId={workspaceId}
          node={node}
          depth={0}
          onSelectFile={onSelectFile}
          selectedPath={selectedPath}
        />
      ))}
      {nodes.length === 0 && (
        <div className="px-4 py-8 text-center">
          <p className="text-[10px] text-muted-foreground/40 font-mono uppercase">Empty directory</p>
        </div>
      )}
    </div>
  );
}
