import { useState, useCallback, useRef } from "react";
import { X, SplitSquareHorizontal } from "lucide-react";
import { ask } from "@tauri-apps/plugin-dialog";
import { useStore, actions } from "@/lib/store";
import { cn } from "@/lib/utils";
import {
  ContextMenu,
  ContextMenuTrigger,
  ContextMenuContent,
  ContextMenuItem,
  ContextMenuSeparator,
} from "@/components/ui/context-menu";

export async function confirmCloseTab(path: string): Promise<boolean> {
  const state = actions.getState();
  const tab = state.tabs.find((t) => t.path === path);
  if (!tab) return true;
  if (tab.content === tab.savedContent) {
    actions.closeTab(path);
    return true;
  }
  const save = await ask(`"${tab.name}" has unsaved changes. Save before closing?`, {
    title: "Unsaved Changes",
    kind: "warning",
    okLabel: "Save",
    cancelLabel: "Don't Save",
  });
  if (save) {
    const { invoke } = await import("@tauri-apps/api/core");
    await invoke("write_file", { path: tab.path, contents: tab.content });
    actions.markSaved(path);
  }
  actions.closeTab(path);
  return true;
}

export function EditorTabs() {
  const { tabs, activeTabPath } = useStore();
  const [dragOverIndex, setDragOverIndex] = useState<number | null>(null);
  const dragIndexRef = useRef<number | null>(null);

  const handleDragStart = useCallback((e: React.DragEvent, index: number) => {
    dragIndexRef.current = index;
    e.dataTransfer.effectAllowed = "move";
    e.dataTransfer.setData("text/plain", String(index));
  }, []);

  const handleDragOver = useCallback((e: React.DragEvent, index: number) => {
    e.preventDefault();
    e.dataTransfer.dropEffect = "move";
    setDragOverIndex(index);
  }, []);

  const handleDrop = useCallback((e: React.DragEvent, toIndex: number) => {
    e.preventDefault();
    const fromIndex = dragIndexRef.current;
    if (fromIndex !== null && fromIndex !== toIndex) {
      actions.reorderTabs(fromIndex, toIndex);
    }
    dragIndexRef.current = null;
    setDragOverIndex(null);
  }, []);

  const handleDragEnd = useCallback(() => {
    dragIndexRef.current = null;
    setDragOverIndex(null);
  }, []);

  if (tabs.length === 0) return null;

  return (
    <div className="flex h-[35px] items-center bg-card overflow-x-auto">
      {tabs.map((tab, index) => {
        const isDirty = tab.content !== tab.savedContent;
        const isActive = tab.path === activeTabPath;

        return (
          <ContextMenu key={tab.path}>
            <ContextMenuTrigger asChild>
              <div
                className={cn(
                  "group flex h-full items-center gap-1 px-3 text-sm cursor-pointer select-none border-r border-card min-w-0 shrink-0 transition-colors",
                  isActive
                    ? "bg-background text-foreground"
                    : "bg-muted text-muted-foreground hover:bg-muted/80",
                  dragOverIndex === index && "border-l-2 border-l-primary"
                )}
                style={{
                  borderTop: isActive ? "1px solid var(--color-primary)" : "1px solid transparent",
                }}
                draggable
                onDragStart={(e) => handleDragStart(e, index)}
                onDragOver={(e) => handleDragOver(e, index)}
                onDrop={(e) => handleDrop(e, index)}
                onDragEnd={handleDragEnd}
                onDragLeave={() => setDragOverIndex(null)}
                onClick={() => actions.setActiveTab(tab.path)}
                onMouseDown={(e) => {
                  if (e.button === 1) {
                    e.preventDefault();
                    confirmCloseTab(tab.path);
                  }
                }}
              >
                <span className="truncate max-w-[120px]">
                  {isDirty && <span className="text-muted-foreground mr-0.5">&middot;</span>}
                  {tab.name}
                </span>
                <button
                  className="ml-1 rounded-sm p-0.5 opacity-0 group-hover:opacity-100 hover:bg-secondary transition-opacity"
                  onClick={(e) => {
                    e.stopPropagation();
                    confirmCloseTab(tab.path);
                  }}
                >
                  <X className="h-3 w-3" />
                </button>
              </div>
            </ContextMenuTrigger>
            <ContextMenuContent>
              <ContextMenuItem onClick={() => confirmCloseTab(tab.path)}>
                Close
              </ContextMenuItem>
              <ContextMenuItem onClick={() => {
                const others = tabs.filter((t) => t.path !== tab.path);
                others.forEach((t) => confirmCloseTab(t.path));
              }}>
                Close Others
              </ContextMenuItem>
              <ContextMenuSeparator />
              <ContextMenuItem onClick={() => actions.setSplitEditor(tab.path)}>
                <SplitSquareHorizontal className="h-4 w-4 mr-2" />
                Open to the Side
              </ContextMenuItem>
            </ContextMenuContent>
          </ContextMenu>
        );
      })}
    </div>
  );
}
