"use client";

import { useState } from "react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@turbostarter/ui-web/tabs";
import { Button } from "@turbostarter/ui-web/button";
import { Icons } from "@turbostarter/ui-web/icons";
import { Input } from "@turbostarter/ui-web/input";
import { toast } from "sonner";
import { api } from "~/lib/api/client";
import { ProjectTree } from "./ProjectTree";
import { RecentList } from "./RecentList";

interface DiagramSidebarProps {
  selectedProjectId: string | null;
  onSelectProject: (projectId: string | null) => void;
}

export function DiagramSidebar({ selectedProjectId, onSelectProject }: DiagramSidebarProps) {
  const [isCreating, setIsCreating] = useState(false);
  const [newProjectName, setNewProjectName] = useState("");
  const queryClient = useQueryClient();

  const createProjectMutation = useMutation({
    mutationFn: async (name: string) => {
      const res = await api.projects.$post({ json: { name } });
      return await res.json();
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["projects"] });
      setIsCreating(false);
      setNewProjectName("");
      toast.success("Project created");
    },
    onError: () => {
      toast.error("Failed to create project");
    },
  });

  const handleCreateProject = () => {
    if (!newProjectName.trim()) return;
    createProjectMutation.mutate(newProjectName.trim());
  };

  return (
    <div className="flex h-full w-64 shrink-0 flex-col border-r">
      <div className="flex items-center justify-between border-b p-3">
        <h2 className="text-sm font-semibold">Diagrams</h2>
        <Button
          variant="ghost"
          size="icon"
          className="h-7 w-7"
          onClick={() => setIsCreating(true)}
          title="New Project"
        >
          <Icons.Plus className="h-4 w-4" />
        </Button>
      </div>

      {isCreating && (
        <div className="border-b p-2">
          <form
            onSubmit={(e) => {
              e.preventDefault();
              handleCreateProject();
            }}
            className="flex gap-1"
          >
            <Input
              value={newProjectName}
              onChange={(e) => setNewProjectName(e.target.value)}
              placeholder="Project name"
              className="h-7 text-xs"
              autoFocus
              onKeyDown={(e) => {
                if (e.key === "Escape") {
                  setIsCreating(false);
                  setNewProjectName("");
                }
              }}
            />
            <Button type="submit" size="icon" className="h-7 w-7 shrink-0" disabled={!newProjectName.trim()}>
              <Icons.Check className="h-3 w-3" />
            </Button>
          </form>
        </div>
      )}

      <Tabs defaultValue="projects" className="flex flex-1 flex-col overflow-hidden">
        <TabsList className="mx-2 mt-2 grid w-auto grid-cols-2">
          <TabsTrigger value="projects" className="text-xs">Projects</TabsTrigger>
          <TabsTrigger value="recent" className="text-xs">Recent</TabsTrigger>
        </TabsList>
        <TabsContent value="projects" className="flex-1 overflow-y-auto p-2">
          <ProjectTree selectedProjectId={selectedProjectId} onSelectProject={onSelectProject} />
        </TabsContent>
        <TabsContent value="recent" className="flex-1 overflow-y-auto p-2">
          <RecentList />
        </TabsContent>
      </Tabs>
    </div>
  );
}
