"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"
import type { Tenant } from "@/types"

interface TenantFormProps {
  properties: { id: string; name: string; units: { id: string; unit_number: string; status: string }[] }[]
  tenant?: Tenant
}

export function TenantForm({ properties, tenant }: TenantFormProps) {
  const router = useRouter()
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState("")
  const [isDirty, setIsDirty] = useState(false)
  const [selectedPropertyId, setSelectedPropertyId] = useState(tenant?.property_id ?? "")
  useWarnUnsaved(isDirty)

  const propertyOptions = [
    { value: "", label: "Select property…" },
    ...properties.map((p) => ({ value: p.id, label: p.name })),
  ]

  const availableUnits = properties
    .find((p) => p.id === selectedPropertyId)
    ?.units.filter((u) => u.status === "vacant" || u.id === tenant?.unit_id) ?? []

  const unitOptions = [
    { value: "", label: "No unit assigned" },
    ...availableUnits.map((u) => ({ value: u.id, label: `Unit ${u.unit_number}` })),
  ]

  async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault()
    setLoading(true)
    setError("")

    const formData = new FormData(e.currentTarget)
    const body: Record<string, unknown> = {
      property_id:             formData.get("property_id"),
      unit_id:                 formData.get("unit_id") || undefined,
      first_name:              formData.get("first_name"),
      last_name:               formData.get("last_name"),
      email:                   formData.get("email") || undefined,
      phone:                   formData.get("phone") || undefined,
      emergency_contact_name:  formData.get("emergency_contact_name") || undefined,
      emergency_contact_phone: formData.get("emergency_contact_phone") || undefined,
      move_in_date:            formData.get("move_in_date") || undefined,
      notes:                   formData.get("notes") || undefined,
    }

    const res = await fetch(
      tenant ? `/api/tenants/${tenant.id}` : "/api/tenants",
      { method: tenant ? "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(tenant ? "Tenant updated" : "Tenant added")
    router.push(`/tenants/${data.id}`)
    router.refresh()
  }

  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"

  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 className="grid grid-cols-2 gap-4">
        <div>
          <label className={lbl}>First Name <span className="text-red-400">*</span></label>
          <input name="first_name" required placeholder="John" defaultValue={tenant?.first_name} className={cls} />
        </div>
        <div>
          <label className={lbl}>Last Name <span className="text-red-400">*</span></label>
          <input name="last_name" required placeholder="Smith" defaultValue={tenant?.last_name} className={cls} />
        </div>
      </div>

      <div className="grid grid-cols-2 gap-4">
        <div>
          <label className={lbl}>Email</label>
          <input name="email" type="email" placeholder="john@email.com" defaultValue={tenant?.email ?? ""} className={cls} />
        </div>
        <div>
          <label className={lbl}>Phone</label>
          <input name="phone" placeholder="+1 555 000 0000" defaultValue={tenant?.phone ?? ""} className={cls} />
        </div>
      </div>

      <div>
        <label className={lbl}>Property <span className="text-red-400">*</span></label>
        <Select
          name="property_id"
          value={selectedPropertyId}
          onChange={setSelectedPropertyId}
          options={propertyOptions}
          required
        />
      </div>

      {selectedPropertyId && (
        <div>
          <label className={lbl}>Unit</label>
          <Select name="unit_id" defaultValue={tenant?.unit_id ?? ""} options={unitOptions} />
          {availableUnits.length === 0 && (
            <p className="mt-1 text-xs text-amber-400">No vacant units in this property.</p>
          )}
        </div>
      )}

      <div>
        <label className={lbl}>Move-in Date</label>
        <input name="move_in_date" type="date" defaultValue={tenant?.move_in_date ?? ""} className={cls} />
      </div>

      <div className="border-t border-white/[0.06] pt-5">
        <p className="mb-3 text-xs font-medium uppercase tracking-wider text-white/30">Emergency Contact</p>
        <div className="grid grid-cols-2 gap-4">
          <div>
            <label className={lbl}>Name</label>
            <input name="emergency_contact_name" placeholder="Jane Smith" defaultValue={tenant?.emergency_contact_name ?? ""} className={cls} />
          </div>
          <div>
            <label className={lbl}>Phone</label>
            <input name="emergency_contact_phone" placeholder="+1 555 000 0001" defaultValue={tenant?.emergency_contact_phone ?? ""} className={cls} />
          </div>
        </div>
      </div>

      <div>
        <label className={lbl}>Notes</label>
        <textarea name="notes" rows={3} placeholder="Optional..." defaultValue={tenant?.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..." : tenant ? "Save Changes" : "Add Tenant"}
        </button>
      </div>
    </form>
  )
}
