"use client"

import { useState } from "react"
import { useRouter } from "next/navigation"
import { toast } from "sonner"
import { Select } from "@/components/ui/select"
import type { Unit } from "@/types"

const statusOptions = [
  { value: "vacant",      label: "Vacant" },
  { value: "occupied",    label: "Occupied" },
  { value: "maintenance", label: "Maintenance" },
  { value: "unavailable", label: "Unavailable" },
]

interface UnitFormProps {
  propertyId: string
  unit?: Unit
  onSuccess?: () => void
}

export function UnitForm({ propertyId, unit, onSuccess }: UnitFormProps) {
  const router = useRouter()
  const [loading, setLoading] = useState(false)
  const [status, setStatus] = useState(unit?.status ?? "vacant")
  const isEditing = Boolean(unit)

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

    const formData = new FormData(e.currentTarget)
    const body = {
      property_id:  propertyId,
      unit_number:  formData.get("unit_number"),
      bedrooms:     Number(formData.get("bedrooms") ?? 1),
      bathrooms:    Number(formData.get("bathrooms") ?? 1),
      sq_ft:        formData.get("sq_ft") ? Number(formData.get("sq_ft")) : undefined,
      rent_amount:  Number(formData.get("rent_amount")),
      status,
      notes:        formData.get("notes") || undefined,
    }

    const res = await fetch(
      isEditing ? `/api/units/${unit!.id}` : "/api/units",
      {
        method: isEditing ? "PATCH" : "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(body),
      }
    )

    setLoading(false)

    if (!res.ok) {
      const data = await res.json().catch(() => null)
      toast.error(data?.error ?? (isEditing ? "Failed to update unit" : "Failed to add unit"))
      return
    }

    toast.success(isEditing ? "Unit updated" : "Unit added")
    if (onSuccess) {
      onSuccess()
    } else {
      router.push(`/properties/${propertyId}`)
      router.refresh()
    }
  }

  const inputClass = "w-full rounded-lg border border-white/10 bg-white/5 px-4 py-2.5 text-sm text-white placeholder:text-white/30 focus:outline-none focus:border-indigo-500/50 focus:ring-1 focus:ring-indigo-500"
  const labelClass = "block text-sm font-medium text-white/70 mb-1.5"

  return (
    <form onSubmit={handleSubmit} className="space-y-5">
      <div className="grid grid-cols-2 gap-4">
        <div>
          <label className={labelClass}>Unit Number *</label>
          <input name="unit_number" required placeholder="e.g. 1A, 101" defaultValue={unit?.unit_number ?? ""} className={inputClass} />
        </div>
        <div>
          <label className={labelClass}>Monthly Rent ($) *</label>
          <input name="rent_amount" type="number" required min={0} step={0.01} placeholder="1500" defaultValue={unit?.rent_amount ?? ""} className={inputClass} />
        </div>
      </div>

      <div className="grid grid-cols-3 gap-4">
        <div>
          <label className={labelClass}>Bedrooms</label>
          <input name="bedrooms" type="number" min={0} defaultValue={unit?.bedrooms ?? 1} className={inputClass} />
        </div>
        <div>
          <label className={labelClass}>Bathrooms</label>
          <input name="bathrooms" type="number" min={0} step={0.5} defaultValue={unit?.bathrooms ?? 1} className={inputClass} />
        </div>
        <div>
          <label className={labelClass}>Sq Ft</label>
          <input name="sq_ft" type="number" min={0} placeholder="Optional" defaultValue={unit?.sq_ft ?? ""} className={inputClass} />
        </div>
      </div>

      <div>
        <label className={labelClass}>Status</label>
        <Select
          options={statusOptions}
          value={status}
          onChange={(v) => setStatus(v as "vacant" | "occupied" | "maintenance" | "unavailable")}
        />
      </div>

      <div>
        <label className={labelClass}>Notes</label>
        <textarea name="notes" rows={3} placeholder="Optional notes..." defaultValue={unit?.notes ?? ""} className={`${inputClass} resize-none`} />
      </div>

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