import { useState, type FormEvent } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { client, type MilestoneResponse } from "@/client";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { useToast } from "@/hooks/use-toast";
import { Milestone, Pencil, Plus, Trash2, X } from "lucide-react";

function MilestoneManageDialog({
  open,
  onOpenChange,
  projectName,
  onSelect,
}: {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  projectName: string;
  onSelect?: (milestone: MilestoneResponse) => void;
}) {
  const qc = useQueryClient();
  const { toast } = useToast();
  const [showForm, setShowForm] = useState(false);
  const [editId, setEditId] = useState<string | null>(null);

  const queryKey = ["milestones", projectName];
  const { data: milestones = [] } = useQuery({
    queryKey,
    queryFn: async () => {
      const res = await client.issuesListMilestones(projectName);
      return res.data ?? [];
    },
    enabled: open,
    retry: false,
  });

  const invalidate = () => qc.invalidateQueries({ queryKey });

  const createMutation = useMutation({
    mutationFn: async (data: { title: string; description?: string | null; due_at?: string | null }) => {
      await client.issuesCreateMilestone(projectName, data);
    },
    onSuccess: () => { invalidate(); setShowForm(false); },
    onError: (e: any) => toast({ title: "Failed", description: String(e?.message ?? e), variant: "destructive" }),
  });

  const updateMutation = useMutation({
    mutationFn: async ({ id, ...data }: { id: string; title?: string; description?: string | null; due_at?: string | null; state?: string }) => {
      await client.issuesUpdateMilestone(projectName, id, data);
    },
    onSuccess: () => { invalidate(); setEditId(null); },
    onError: (e: any) => toast({ title: "Failed", description: String(e?.message ?? e), variant: "destructive" }),
  });

  const deleteMutation = useMutation({
    mutationFn: async (id: string) => {
      await client.issuesDeleteMilestone(projectName, id);
    },
    onSuccess: () => invalidate(),
    onError: (e: any) => toast({ title: "Failed", description: String(e?.message ?? e), variant: "destructive" }),
  });

  const openMilestones = milestones.filter((m) => m.state === "open");
  const closedMilestones = milestones.filter((m) => m.state === "closed");

  const renderList = (items: MilestoneResponse[], _closed: boolean) =>
    items.map((m) => (
      <div key={m.id}>
        {editId === m.id ? (
          <MilestoneForm
            initialTitle={m.title}
            initialDescription={m.description}
            initialDueAt={m.due_at}
            onSubmit={(data) => updateMutation.mutate({ id: m.id, ...data })}
            onCancel={() => setEditId(null)}
            submitting={updateMutation.isPending}
          />
        ) : (
          <div className="flex items-center gap-2 rounded py-1.5 px-1 hover:bg-muted/50">
            <Milestone className="size-4 shrink-0 text-muted-foreground" />
            <div className="flex-1 min-w-0">
              <span className="text-[12px] font-heading font-medium text-foreground">{m.title}</span>
              {m.due_at && (
                <span className="ml-2 font-mono text-[10px] text-muted-foreground">
                  Due {new Date(m.due_at).toLocaleDateString()}
                </span>
              )}
              {m.description && <p className="text-[11px] text-muted-foreground truncate">{m.description}</p>}
            </div>
            {onSelect && (
              <Button className="h-6 px-2 text-[11px]" variant="ghost" onClick={() => { onSelect(m); onOpenChange(false); }}>
                Select
              </Button>
            )}
            <button className="grid size-6 place-items-center rounded text-muted-foreground hover:text-foreground cursor-pointer" onClick={() => setEditId(m.id)}>
              <Pencil className="size-3" />
            </button>
            <AlertDialog>
              <AlertDialogTrigger asChild>
                <button className="grid size-6 place-items-center rounded text-muted-foreground hover:text-destructive cursor-pointer">
                  <Trash2 className="size-3" />
                </button>
              </AlertDialogTrigger>
              <AlertDialogContent>
                <AlertDialogHeader>
                  <AlertDialogTitle>Delete &ldquo;{m.title}&rdquo;?</AlertDialogTitle>
                  <AlertDialogDescription>This will remove it from all issues.</AlertDialogDescription>
                </AlertDialogHeader>
                <AlertDialogFooter>
                  <AlertDialogCancel>Cancel</AlertDialogCancel>
                  <AlertDialogAction onClick={() => deleteMutation.mutate(m.id)}>Delete</AlertDialogAction>
                </AlertDialogFooter>
              </AlertDialogContent>
            </AlertDialog>
          </div>
        )}
      </div>
    ));

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-md">
        <DialogHeader className="flex flex-row items-center justify-between">
          <DialogTitle>Manage milestones</DialogTitle>
          <Button className="h-7 px-2 text-[12px]" variant="ghost" onClick={() => setShowForm(true)}>
            <Plus className="size-3.5" />
          </Button>
        </DialogHeader>

        {showForm && (
          <MilestoneForm
            onSubmit={(data) => createMutation.mutate(data)}
            onCancel={() => setShowForm(false)}
            submitting={createMutation.isPending}
          />
        )}

        <div className="max-h-[350px] space-y-1 overflow-y-auto">
          {milestones.length === 0 && !showForm && (
            <p className="text-center text-[12px] text-muted-foreground py-4">No milestones yet</p>
          )}
          {renderList(openMilestones, false)}
          {closedMilestones.length > 0 && (
            <>
              <p className="font-mono text-[10px] uppercase tracking-wider text-muted-foreground mt-2 mb-1 px-1">Closed</p>
              {renderList(closedMilestones, true)}
            </>
          )}
        </div>
      </DialogContent>
    </Dialog>
  );
}

function MilestoneForm({
  initialTitle = "",
  initialDescription = "",
  initialDueAt = "",
  onSubmit,
  onCancel,
  submitting,
}: {
  initialTitle?: string;
  initialDescription?: string | null;
  initialDueAt?: string | null;
  onSubmit: (data: { title: string; description?: string | null; due_at?: string | null }) => void;
  onCancel: () => void;
  submitting: boolean;
}) {
  const handleSubmit = (e: FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    const form = new FormData(e.currentTarget);
    const title = (form.get("title") as string).trim();
    const description = (form.get("description") as string)?.trim() || null;
    const dueAt = (form.get("due_at") as string) || null;
    if (!title) return;
    onSubmit({ title, description, due_at: dueAt });
  };

  return (
    <form className="rounded border border-border p-3 mb-2 space-y-2 bg-muted/20" onSubmit={(e) => void handleSubmit(e)}>
      <div className="flex items-center gap-2">
        <Input className="h-8 text-[12px]" name="title" placeholder="Milestone title" defaultValue={initialTitle} required autoFocus />
      </div>
      <Input className="h-8 text-[12px]" name="description" placeholder="Description (optional)" defaultValue={initialDescription ?? ""} />
      <Input className="h-8 text-[12px]" name="due_at" type="date" defaultValue={initialDueAt ? initialDueAt.slice(0, 10) : ""} />
      <div className="flex items-center justify-end gap-2">
        <Button className="h-7 px-3 text-[11px]" variant="outline" type="button" onClick={onCancel}>
          <X className="size-3" />
        </Button>
        <Button className="h-7 px-3 text-[11px]" disabled={submitting} type="submit">
          {submitting ? "Saving..." : "Save"}
        </Button>
      </div>
    </form>
  );
}

export { MilestoneManageDialog };
