"use client"

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

const STATUSES = [
  { value: "pending", label: "Pending" },
  { value: "paid",    label: "Paid"    },
  { value: "overdue", label: "Overdue" },
  { value: "partial", label: "Partial" },
  { value: "waived",  label: "Waived"  },
]

const PAYMENT_METHODS = [
  { value: "",               label: "Select method…"  },
  { value: "cash",           label: "Cash"            },
  { value: "bank_transfer",  label: "Bank Transfer"   },
  { value: "check",          label: "Check"           },
  { value: "stripe",         label: "Stripe"          },
]

export function RentPaymentForm({ tenants }: { tenants: any[] }) {
  const router = useRouter()
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState("")
  const [selectedTenantId, setSelectedTenantId] = useState("")

  const tenantOptions = [
    { value: "", label: "Select tenant…" },
    ...tenants.map((t: any) => ({
      value: t.id,
      label: `${t.first_name} ${t.last_name}${t.property?.name ? ` — ${t.property.name}` : ""}${t.unit ? ` (Unit ${t.unit.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 formData = new FormData(e.currentTarget)
    const body = {
      tenant_id:      formData.get("tenant_id"),
      property_id:    selectedTenant?.property?.id,
      unit_id:        selectedTenant?.unit_id || undefined,
      amount:         Number(formData.get("amount")),
      due_date:       formData.get("due_date"),
      paid_date:      formData.get("paid_date") || undefined,
      status:         formData.get("status"),
      payment_method: formData.get("payment_method") || undefined,
      notes:          formData.get("notes") || undefined,
    }

    const res = await fetch("/api/rent", {
      method: "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
    }

    toast.success("Payment recorded")
    router.push("/rent")
    router.refresh()
  }

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

  return (
    <form onSubmit={handleSubmit} 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={setSelectedTenantId}
          options={tenantOptions}
          required
        />
      </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={selectedTenant?.unit?.rent_amount ?? ""}
            className={cls}
          />
        </div>
        <div>
          <label className={lbl}>Status <span className="text-red-400">*</span></label>
          <Select name="status" defaultValue="pending" options={STATUSES} required />
        </div>
      </div>

      <div className="grid grid-cols-2 gap-4">
        <div>
          <label className={lbl}>Due Date <span className="text-red-400">*</span></label>
          <input name="due_date" type="date" required defaultValue={today} className={cls} />
        </div>
        <div>
          <label className={lbl}>Paid Date</label>
          <input name="paid_date" type="date" className={cls} />
        </div>
      </div>

      <div>
        <label className={lbl}>Payment Method</label>
        <Select name="payment_method" defaultValue="" options={PAYMENT_METHODS} />
      </div>

      <div>
        <label className={lbl}>Notes</label>
        <textarea name="notes" rows={2} placeholder="Optional..." 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..." : "Record Payment"}
        </button>
      </div>
    </form>
  )
}
