"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@turbostarter/ui-web/dialog";
import { Button } from "@turbostarter/ui-web/button";
import { Input } from "@turbostarter/ui-web/input";
import { Icons } from "@turbostarter/ui-web/icons";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@turbostarter/ui-web/select";
import { toast } from "sonner";
import { api } from "~/lib/api/client";
import { pathsConfig } from "~/config/paths";
import { diagramTypeConfig } from "./DiagramCard";

import type { ReactNode } from "react";

const diagramTypes = ["bpmn", "er", "orgchart", "architecture", "sequence", "flowchart"] as const;
type DiagramType = (typeof diagramTypes)[number];

interface CreateDiagramDialogProps {
  children: ReactNode;
}

export function CreateDiagramDialog({ children }: CreateDiagramDialogProps) {
  const [open, setOpen] = useState(false);
  const [title, setTitle] = useState("");
  const [selectedType, setSelectedType] = useState<DiagramType>("flowchart");
  const [selectedProjectId, setSelectedProjectId] = useState<string | undefined>(undefined);
  const router = useRouter();
  const queryClient = useQueryClient();

  const { data: projectsData } = useQuery({
    queryKey: ["projects"],
    queryFn: async () => {
      const res = await api.projects.$get();
      return await res.json();
    },
  });

  const projects = projectsData?.data ?? [];

  const createMutation = useMutation({
    mutationFn: async (input: { title: string; type: DiagramType; projectId?: string }) => {
      const res = await api.diagrams.$post({ json: input });
      return await res.json();
    },
    onSuccess: (data) => {
      queryClient.invalidateQueries({ queryKey: ["diagrams"] });
      setOpen(false);
      setTitle("");
      setSelectedType("flowchart");
      setSelectedProjectId(undefined);
      if (data.data) {
        router.push(pathsConfig.dashboard.user.diagram(data.data.id));
      }
    },
    onError: () => {
      toast.error("Failed to create diagram. Please try again.");
    },
  });

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (!title.trim()) return;
    createMutation.mutate({
      title: title.trim(),
      type: selectedType,
      projectId: selectedProjectId,
    });
  };

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>{children}</DialogTrigger>
      <DialogContent className="sm:max-w-lg">
        <DialogHeader>
          <DialogTitle>Create New Diagram</DialogTitle>
        </DialogHeader>
        <form onSubmit={handleSubmit} className="space-y-6">
          <div className="space-y-2">
            <label htmlFor="diagram-title" className="text-sm font-medium">
              Title
            </label>
            <Input
              id="diagram-title"
              placeholder="My diagram"
              value={title}
              onChange={(e) => setTitle(e.target.value)}
              autoFocus
            />
          </div>

          <div className="space-y-2">
            <label className="text-sm font-medium">Project</label>
            <Select
              value={selectedProjectId ?? "none"}
              onValueChange={(v) => setSelectedProjectId(v === "none" ? undefined : v)}
            >
              <SelectTrigger className="w-full">
                <SelectValue placeholder="No project (Unorganized)" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="none">No project (Unorganized)</SelectItem>
                {projects.map((p) => (
                  <SelectItem key={p.id} value={p.id}>{p.name}</SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          <div className="space-y-2">
            <label className="text-sm font-medium">Diagram Type</label>
            <div className="grid grid-cols-3 gap-2">
              {diagramTypes.map((type) => {
                const config = diagramTypeConfig[type];
                const TypeIcon = config.icon;
                const isSelected = selectedType === type;
                return (
                  <button
                    key={type}
                    type="button"
                    onClick={() => setSelectedType(type)}
                    className={`flex flex-col items-center gap-1.5 rounded-lg border-2 p-3 text-sm transition-colors ${
                      isSelected
                        ? "border-primary bg-primary/5"
                        : "border-transparent bg-muted/50 hover:bg-muted"
                    }`}
                  >
                    <TypeIcon className={`h-5 w-5 ${config.color}`} />
                    <span className="font-medium">{config.label}</span>
                  </button>
                );
              })}
            </div>
          </div>

          <div className="flex justify-end gap-2">
            <Button
              type="button"
              variant="outline"
              onClick={() => setOpen(false)}
            >
              Cancel
            </Button>
            <Button
              type="submit"
              disabled={!title.trim() || createMutation.isPending}
            >
              {createMutation.isPending && (
                <Icons.Loader2 className="mr-2 h-4 w-4 animate-spin" />
              )}
              Create
            </Button>
          </div>
        </form>
      </DialogContent>
    </Dialog>
  );
}
