"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<HTMLFormElement>) {
    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(lease ? `/leases/${lease.id}` : "/leases")
    router.refresh()
  }

  return (
    <form onSubmit={handleSubmit} onChange={() => setIsDirty(true)} className="space-y-5 rounded-xl border border-white/[0.06] bg-[#16161f] p-6">
      {error && <div className="rounded-lg border border-red-500/20 bg-red-500/10 px-4 py-3 text-sm text-red-400">{error}</div>}

      <div>
        <label className={lbl}>Tenant <span className="text-red-400">*</span></label>
        <Select
          name="tenant_id"
          value={selectedTenantId}
          onChange={(val) => {
            setSelectedTenantId(val)
            const t = tenants.find((t: any) => t.id === val)
            if (t) setSelectedPropertyId(t.property_id ?? "")
          }}
          options={tenantOptions}
          required
        />
      </div>

      <div className="grid grid-cols-2 gap-4">
        <div>
          <label className={lbl}>Property <span className="text-red-400">*</span></label>
          <Select
            name="property_id"
            value={selectedPropertyId}
            onChange={setSelectedPropertyId}
            options={propertyOptions}
            required
          />
        </div>
        <div>
          <label className={lbl}>Unit</label>
          <Select
            name="unit_id"
            defaultValue={lease?.unit_id ?? prefill?.unit_id ?? selectedTenant?.unit_id ?? ""}
            options={unitOptions}
          />
        </div>
      </div>

      <div className="grid grid-cols-2 gap-4">
        <div>
          <label className={lbl}>Lease Start <span className="text-red-400">*</span></label>
          <input name="lease_start" type="date" required defaultValue={lease?.lease_start} className={cls} />
        </div>
        <div>
          <label className={lbl}>Lease End <span className="text-red-400">*</span></label>
          <input name="lease_end" type="date" required defaultValue={lease?.lease_end} className={cls} />
        </div>
      </div>

      <div className="grid grid-cols-2 gap-4">
        <div>
          <label className={lbl}>Monthly Rent ($) <span className="text-red-400">*</span></label>
          <input name="rent_amount" type="number" step="0.01" min="0" required placeholder="0.00" defaultValue={lease?.rent_amount ?? prefill?.rent_amount ?? ""} className={cls} />
        </div>
        <div>
          <label className={lbl}>Security Deposit ($)</label>
          <input name="security_deposit" type="number" step="0.01" min="0" placeholder="0.00" defaultValue={lease?.security_deposit ?? ""} className={cls} />
        </div>
      </div>

      <div className="grid grid-cols-2 gap-4">
        <div>
          <label className={lbl}>Lease Type</label>
          <Select name="lease_type" defaultValue={lease?.lease_type ?? "fixed"} options={LEASE_TYPES} />
        </div>
        <div className="flex items-center gap-3 pt-6">
          <input name="auto_renew" type="checkbox" id="auto_renew" defaultChecked={lease?.auto_renew} className="h-4 w-4 rounded border-white/20 bg-white/5 accent-indigo-600" />
          <label htmlFor="auto_renew" className="text-sm text-white/70">Auto-renew</label>
        </div>
      </div>

      <div>
        <label className={lbl}>Notes</label>
        <textarea name="notes" rows={2} placeholder="Optional..." defaultValue={lease?.notes ?? ""} className={cls + " resize-none"} />
      </div>

      <div className="flex gap-3 pt-2">
        <button type="button" onClick={() => router.back()} className="rounded-lg border border-white/10 px-5 py-2.5 text-sm text-white/60 hover:text-white transition">Cancel</button>
        <button type="submit" disabled={loading} className="flex-1 rounded-lg bg-indigo-600 px-5 py-2.5 text-sm font-semibold text-white hover:bg-indigo-500 disabled:opacity-50 transition">
          {loading ? "Saving..." : lease ? "Save Changes" : "Add Lease"}
        </button>
      </div>
    </form>
  )
}
