"use client" import { useState } from "react" import { useRouter } from "next/navigation" import { toast } from "sonner" import { useWarnUnsaved } from "@/lib/hooks/use-warn-unsaved" import { Select } from "@/components/ui/select" const LEASE_TYPES = [ { value: "fixed", label: "Fixed Term" }, { value: "month_to_month", label: "Month-to-Month" }, ] export function LeaseForm({ tenants, properties, lease, prefill }: { tenants: any[]; properties: any[]; lease?: any prefill?: { tenant_id?: string; property_id?: string; unit_id?: string; rent_amount?: string } }) { const router = useRouter() const [loading, setLoading] = useState(false) const [error, setError] = useState("") const [selectedTenantId, setSelectedTenantId] = useState(lease?.tenant_id ?? prefill?.tenant_id ?? "") const [selectedPropertyId, setSelectedPropertyId] = useState(lease?.property_id ?? prefill?.property_id ?? "") const [isDirty, setIsDirty] = useState(false) useWarnUnsaved(isDirty) const tenantOptions = [ { value: "", label: "Select tenant…" }, ...tenants.map((t: any) => ({ value: t.id, label: `${t.first_name} ${t.last_name}` })), ] const propertyOptions = [ { value: "", label: "Select property…" }, ...properties.map((p: any) => ({ value: p.id, label: p.name })), ] const units = properties.find((p: any) => p.id === selectedPropertyId)?.units ?? [] const unitOptions = [ { value: "", label: "No unit" }, ...units.map((u: any) => ({ value: u.id, label: `Unit ${u.unit_number}` })), ] const selectedTenant = tenants.find((t: any) => t.id === selectedTenantId) const cls = "w-full rounded-lg border border-white/10 bg-white/5 px-4 py-2.5 text-sm text-white placeholder-white/30 outline-none ring-indigo-500 transition focus:border-indigo-500/50 focus:ring-1" const lbl = "mb-1.5 block text-sm font-medium text-white/70" async function handleSubmit(e: React.FormEvent) { e.preventDefault() setLoading(true) setError("") const fd = new FormData(e.currentTarget) const body = { tenant_id: fd.get("tenant_id"), property_id: fd.get("property_id"), unit_id: fd.get("unit_id") || undefined, lease_start: fd.get("lease_start"), lease_end: fd.get("lease_end"), rent_amount: Number(fd.get("rent_amount")), security_deposit: fd.get("security_deposit") ? Number(fd.get("security_deposit")) : undefined, lease_type: fd.get("lease_type"), auto_renew: fd.get("auto_renew") === "on", notes: fd.get("notes") || undefined, } const res = await fetch(lease ? `/api/leases/${lease.id}` : "/api/leases", { method: lease ? "PATCH" : "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body), }) const data = await res.json() setLoading(false) if (!res.ok) { setError(typeof data.error === "string" ? data.error : "Something went wrong") return } setIsDirty(false) toast.success(lease ? "Lease updated" : "Lease created") router.push("/leases") router.refresh() } return (
setIsDirty(true)} className="space-y-5 rounded-xl border border-white/[0.06] bg-[#16161f] p-6"> {error &&
{error}
}