"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 { Property } from "@/types"

const PROPERTY_TYPES = [
  { value: "residential", label: "Residential" },
  { value: "commercial",  label: "Commercial"  },
  { value: "mixed",       label: "Mixed Use"   },
]

interface PropertyFormProps {
  property?: Property
}

export function PropertyForm({ property }: PropertyFormProps) {
  const router = useRouter()
  const [loading, setLoading] = useState(false)
  const [error, setError]     = useState("")
  const [isDirty, setIsDirty] = useState(false)
  useWarnUnsaved(isDirty)

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

    const formData = new FormData(e.currentTarget)
    const body = {
      name:          formData.get("name"),
      address_line1: formData.get("address_line1"),
      address_line2: formData.get("address_line2") || undefined,
      city:          formData.get("city"),
      state:         formData.get("state") || undefined,
      postal_code:   formData.get("postal_code") || undefined,
      country:       formData.get("country") || "US",
      property_type: formData.get("property_type"),
      total_units:   Number(formData.get("total_units")) || 1,
      notes:         formData.get("notes") || undefined,
    }

    const res = await fetch(
      property ? `/api/properties/${property.id}` : "/api/properties",
      { method: property ? "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(property ? "Property updated" : "Property added")
    router.push(`/properties/${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>
        <label className={lbl}>Property Name <span className="text-red-400">*</span></label>
        <input name="name" required placeholder="Sunset Apartments" defaultValue={property?.name} className={cls} />
      </div>

      <div className="grid grid-cols-2 gap-4">
        <div>
          <label className={lbl}>Type</label>
          <Select
            name="property_type"
            defaultValue={property?.property_type ?? "residential"}
            options={PROPERTY_TYPES}
          />
        </div>
        <div>
          <label className={lbl}>Total Units</label>
          <input name="total_units" type="number" min="1" defaultValue={String(property?.total_units ?? 1)} className={cls} />
        </div>
      </div>

      <div>
        <label className={lbl}>Address Line 1 <span className="text-red-400">*</span></label>
        <input name="address_line1" required placeholder="123 Main Street" defaultValue={property?.address_line1} className={cls} />
      </div>

      <div>
        <label className={lbl}>Address Line 2</label>
        <input name="address_line2" placeholder="Apt, Suite, Floor (optional)" defaultValue={property?.address_line2 ?? ""} className={cls} />
      </div>

      <div className="grid grid-cols-2 gap-4">
        <div>
          <label className={lbl}>City <span className="text-red-400">*</span></label>
          <input name="city" required placeholder="New York" defaultValue={property?.city} className={cls} />
        </div>
        <div>
          <label className={lbl}>State</label>
          <input name="state" placeholder="NY" defaultValue={property?.state ?? ""} className={cls} />
        </div>
      </div>

      <div className="grid grid-cols-2 gap-4">
        <div>
          <label className={lbl}>Postal Code</label>
          <input name="postal_code" placeholder="10001" defaultValue={property?.postal_code ?? ""} className={cls} />
        </div>
        <div>
          <label className={lbl}>Country</label>
          <input name="country" defaultValue={property?.country ?? "US"} className={cls} />
        </div>
      </div>

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