import { useState, type FormEvent } from "react";
import { useQueryClient } from "@tanstack/react-query";
import { client, type IssueResponse } from "@/client";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogClose } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { useToast } from "@/hooks/use-toast";

export default function EditIssueDialog({
  open,
  onOpenChange,
  issue,
  projectName,
  queryKey,
}: {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  issue: IssueResponse;
  projectName: string;
  queryKey: unknown[];
}) {
  const qc = useQueryClient();
  const { toast } = useToast();
  const [submitting, setSubmitting] = useState(false);

  const handleSubmit = async (e: FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    setSubmitting(true);
    const form = new FormData(e.currentTarget);
    const title = (form.get("title") as string) || null;
    const body = (form.get("body") as string) || null;
    const priority = (form.get("priority") as string) || null;
    const dueAt = (form.get("due_at") as string) || null;

    try {
      await client.issuesUpdateIssue(projectName, issue.number, {
        title,
        body,
        priority,
        due_at: dueAt,
      });
      qc.invalidateQueries({ queryKey });
      onOpenChange(false);
    } catch (err: any) {
      toast({ title: "Failed to update issue", description: String(err?.message ?? err), variant: "destructive" });
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-xl">
        <DialogHeader>
          <DialogTitle>Edit issue # {issue.number}</DialogTitle>
        </DialogHeader>
        <form className="space-y-4" onSubmit={(e) => void handleSubmit(e)}>
          <div>
            <label className="text-[13px] font-medium text-foreground">Title</label>
            <Input
              className="mt-1 h-9 text-[14px] font-heading font-semibold"
              name="title"
              defaultValue={issue.title}
              required
            />
          </div>
          <div>
            <label className="text-[13px] font-medium text-foreground">Description</label>
            <Textarea
              className="mt-1 min-h-[150px] text-[13px]"
              name="body"
              defaultValue={issue.body ?? ""}
              placeholder="Leave a comment... Markdown is supported"
            />
          </div>
          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="text-[12px] font-medium text-foreground">Priority</label>
              <Select name="priority" defaultValue={issue.priority ?? "normal"}>
                <SelectTrigger className="mt-1 w-full h-8 text-[12px]">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="critical">Critical</SelectItem>
                  <SelectItem value="high">High</SelectItem>
                  <SelectItem value="normal">Normal</SelectItem>
                  <SelectItem value="low">Low</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div>
              <label className="text-[12px] font-medium text-foreground">Due date</label>
              <Input
                className="mt-1 h-8 w-full text-[12px]"
                name="due_at"
                type="date"
                defaultValue={issue.due_at ? issue.due_at.slice(0, 10) : ""}
              />
            </div>
          </div>
          <div className="flex items-center justify-end gap-2 pt-2">
            <DialogClose asChild>
              <Button className="h-8 px-3 text-[12px]" variant="outline">Cancel</Button>
            </DialogClose>
            <Button className="h-8 px-3 text-[12px]" disabled={submitting} type="submit">
              {submitting ? "Saving..." : "Save changes"}
            </Button>
          </div>
        </form>
      </DialogContent>
    </Dialog>
  );
}
