"use client";

import { useState, useTransition } from "react";
import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { createList } from "@/modules/lists/server/actions";

type Props = {
  open: boolean;
  onOpenChange: (open: boolean) => void;
};

export function ListCreateDialog({ open, onOpenChange }: Props) {
  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-md">
        {open ? <ListCreateForm onDone={() => onOpenChange(false)} /> : null}
      </DialogContent>
    </Dialog>
  );
}

function ListCreateForm({ onDone }: { onDone: () => void }) {
  const [type, setType] = useState("shopping");
  const [name, setName] = useState("");
  const [isPending, startTransition] = useTransition();

  function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    if (!type.trim() || !name.trim()) return;
    startTransition(async () => {
      await createList({ type: type.trim(), name: name.trim() });
      onDone();
    });
  }

  return (
    <>
      <DialogHeader>
        <DialogTitle>New list</DialogTitle>
      </DialogHeader>
      <form id="quick-add-new-list-form" onSubmit={handleSubmit} className="grid gap-3">
        <div className="space-y-1.5">
          <Label htmlFor="qa-new-list-type">Type</Label>
          <Input
            id="qa-new-list-type"
            value={type}
            onChange={(e) => setType(e.target.value)}
            required
          />
        </div>
        <div className="space-y-1.5">
          <Label htmlFor="qa-new-list-name">Name</Label>
          <Input
            id="qa-new-list-name"
            value={name}
            onChange={(e) => setName(e.target.value)}
            required
          />
        </div>
      </form>
      <DialogFooter>
        <Button
          type="submit"
          form="quick-add-new-list-form"
          disabled={!type.trim() || !name.trim() || isPending}
        >
          Create list
        </Button>
      </DialogFooter>
    </>
  );
}
