"use client";

import { useState, useTransition } from "react";
import { Home, Loader2 } from "lucide-react";
import { toast } from "sonner";

import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { createMyFamily } from "../actions";

export function CreateFamilyDialog({
  defaultFamilyName,
}: {
  defaultFamilyName: string;
}) {
  const [open, setOpen] = useState(false);
  const [isPending, startTransition] = useTransition();

  function handleSubmit(formData: FormData) {
    startTransition(async () => {
      const result = await createMyFamily({
        familyName: String(formData.get("familyName") ?? ""),
      });

      if (result.error) {
        toast.error(result.error);
        return;
      }

      toast.success("Haushalt angelegt.");
      setOpen(false);
    });
  }

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>
        <Button type="button" size="sm" className="gap-2">
          <Home className="h-4 w-4" />
          Haushalt anlegen
        </Button>
      </DialogTrigger>
      <DialogContent>
        <form action={handleSubmit}>
          <DialogHeader>
            <DialogTitle>Eigenen Haushalt anlegen</DialogTitle>
            <DialogDescription>
              Dein Account wird diesem Haushalt zugeordnet. Danach kannst du
              deine Kinder im Profil verwalten.
            </DialogDescription>
          </DialogHeader>

          <div className="grid gap-2 py-4">
            <Label htmlFor="familyName">Haushaltsname</Label>
            <Input
              id="familyName"
              name="familyName"
              defaultValue={defaultFamilyName}
              placeholder="Familie Beispiel"
              required
            />
          </div>

          <DialogFooter>
            <Button
              type="button"
              variant="ghost"
              onClick={() => setOpen(false)}
              disabled={isPending}
            >
              Abbrechen
            </Button>
            <Button type="submit" disabled={isPending}>
              {isPending && <Loader2 className="h-4 w-4 animate-spin" />}
              Haushalt speichern
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
