"use client"; import { useState } from "react"; import { useRouter } from "next/navigation"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { Textarea } from "@/components/ui/textarea"; import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, } from "@/components/ui/dialog"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@/components/ui/select"; import { useToast } from "@/hooks/use-toast"; import { Plus, Pencil } from "lucide-react"; import { COMMON_SPECIES } from "@/lib/animals/animal-fields"; export type LocationOpt = { id: string; name: string }; export type AnimalFields = { id?: string; name: string; species: string; breed: string; sex: string; locationId: string; birthdate: string; acquiredAt: string; source: string; notes: string; }; export function blankAnimal(): AnimalFields { return { name: "", species: "", breed: "", sex: "", locationId: "", birthdate: "", acquiredAt: "", source: "", notes: "" }; } const NONE = "__none__"; function AnimalDialog({ trigger, title, initial, locations }: { trigger: React.ReactNode; title: string; initial: AnimalFields; locations: LocationOpt[]; }) { const [open, setOpen] = useState(false); const [f, setF] = useState(initial); const [busy, setBusy] = useState(false); const [error, setError] = useState(""); const router = useRouter(); const { toast } = useToast(); function set(k: K, v: AnimalFields[K]) { setF((p) => ({ ...p, [k]: v })); } async function submit(e: React.FormEvent) { e.preventDefault(); if (!f.name.trim()) { setError("Please give the animal a name."); return; } setError(""); setBusy(true); const payload = { name: f.name.trim(), species: f.species.trim() || undefined, breed: f.breed.trim() || undefined, sex: f.sex.trim() || undefined, locationId: f.locationId || null, birthdate: f.birthdate || null, acquiredAt: f.acquiredAt || null, source: f.source.trim() || undefined, notes: f.notes.trim() || undefined, }; const res = await fetch(f.id ? `/api/v1/animals/${f.id}` : "/api/v1/animals", { method: f.id ? "PATCH" : "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(payload), }); setBusy(false); if (!res.ok) { const err = await res.json().catch(() => ({})); toast({ title: "Error", description: err.error ?? "Could not save.", variant: "destructive" }); return; } toast({ title: f.id ? "Saved!" : "Added!" }); setOpen(false); router.refresh(); } return ( <> { setF(initial); setOpen(true); }}>{trigger} {title}
set("name", e.target.value)} placeholder="Bella" /> {error &&

{error}

}
set("species", e.target.value)} placeholder="Dog" /> {COMMON_SPECIES.map((s) =>
set("breed", e.target.value)} placeholder="Border collie" />
set("sex", e.target.value)} placeholder="Female" />
set("birthdate", e.target.value)} />
set("acquiredAt", e.target.value)} />
set("source", e.target.value)} placeholder="Breeder, shelter, hatchery…" />