"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 CATEGORIES = [
  { value: "repairs",    label: "Repairs"    },
  { value: "utilities",  label: "Utilities"  },
  { value: "insurance",  label: "Insurance"  },
  { value: "mortgage",   label: "Mortgage"   },
  { value: "taxes",      label: "Taxes"      },
  { value: "management", label: "Management" },
  { value: "supplies",   label: "Supplies"   },
  { value: "other",      label: "Other"      },
]

const RECURRENCE = [
  { value: "monthly",   label: "Monthly"   },
  { value: "quarterly", label: "Quarterly" },
  { value: "yearly",    label: "Yearly"    },
]

export function ExpenseForm({ properties, expense }: { properties: any[]; expense?: any }) {
  const router = useRouter()
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState("")
  const [selectedPropertyId, setSelectedPropertyId] = useState(expense?.property_id ?? "")
  const [isRecurring, setIsRecurring] = useState(expense?.is_recurring ?? false)
  const [isDirty, setIsDirty] = useState(false)
  useWarnUnsaved(isDirty)

  const propertyOptions = properties.map((p: any) => ({ value: p.id, label: p.name }))
  const units = properties.find((p: any) => p.id === selectedPropertyId)?.units ?? []
  const unitOptions = [
    { value: "", label: "Whole property" },
    ...units.map((u: any) => ({ value: u.id, label: `Unit ${u.unit_number}` })),
  ]

  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 = {
      property_id:  fd.get("property_id"),
      unit_id:      fd.get("unit_id") || undefined,
      category:     fd.get("category"),
      description:  fd.get("description"),
      amount:       Number(fd.get("amount")),
      expense_date: fd.get("expense_date"),
      vendor:       fd.get("vendor") || undefined,
      is_recurring: fd.get("is_recurring") === "on",
      recurrence:   fd.get("recurrence") || undefined,
      notes:        fd.get("notes") || undefined,
    }

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

  const today = new Date().toISOString().slice(0, 10)

  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}>Description <span className="text-red-400">*</span></label>
        <input name="description" required placeholder="e.g. Plumbing repair" defaultValue={expense?.description} className={cls} />
      </div>

      <div className="grid grid-cols-2 gap-4">
        <div>
          <label className={lbl}>Amount ($) <span className="text-red-400">*</span></label>
          <input name="amount" type="number" step="0.01" min="0" required placeholder="0.00" defaultValue={expense?.amount} className={cls} />
        </div>
        <div>
          <label className={lbl}>Date <span className="text-red-400">*</span></label>
          <input name="expense_date" type="date" required defaultValue={expense?.expense_date ?? today} className={cls} />
        </div>
      </div>

      <div className="grid grid-cols-2 gap-4">
        <div>
          <label className={lbl}>Category <span className="text-red-400">*</span></label>
          <Select name="category" defaultValue={expense?.category ?? "repairs"} options={CATEGORIES} required />
        </div>
        <div>
          <label className={lbl}>Vendor</label>
          <input name="vendor" placeholder="Vendor / contractor" defaultValue={expense?.vendor ?? ""} 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={[{ value: "", label: "Select property…" }, ...propertyOptions]}
          required
        />
      </div>

      {selectedPropertyId && units.length > 0 && (
        <div>
          <label className={lbl}>Unit (optional)</label>
          <Select name="unit_id" defaultValue={expense?.unit_id ?? ""} options={unitOptions} />
        </div>
      )}

      <div className="flex items-center gap-3">
        <input
          name="is_recurring"
          type="checkbox"
          id="is_recurring"
          checked={isRecurring}
          onChange={(e) => setIsRecurring(e.target.checked)}
          className="h-4 w-4 rounded accent-indigo-600"
        />
        <label htmlFor="is_recurring" className="text-sm text-white/70">Recurring expense</label>
      </div>

      {isRecurring && (
        <div>
          <label className={lbl}>Recurrence</label>
          <Select name="recurrence" defaultValue={expense?.recurrence ?? "monthly"} options={RECURRENCE} />
        </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..." : expense ? "Save Changes" : "Add Expense"}
        </button>
      </div>
    </form>
  )
}
