"use client"

import { useState } from "react"
import { useRouter } from "next/navigation"
import { Zap, CheckCircle2, AlertCircle, ChevronLeft, ChevronRight, Users } from "lucide-react"
import { formatCurrency } from "@/lib/utils"

function monthLabel(year: number, month: number) {
  return new Date(year, month, 1).toLocaleDateString("en-US", { month: "long", year: "numeric" })
}

export function BulkGenerateForm({ leases }: { leases: any[] }) {
  const router = useRouter()
  const now = new Date()
  const [year, setYear]     = useState(now.getFullYear())
  const [month, setMonth]   = useState(now.getMonth())
  const [loading, setLoading] = useState(false)
  const [result, setResult] = useState<{ created: number; skipped: number; message: string } | null>(null)
  const [error, setError]   = useState("")

  function prevMonth() {
    if (month === 0) { setMonth(11); setYear(y => y - 1) } else setMonth(m => m - 1)
  }
  function nextMonth() {
    if (month === 11) { setMonth(0); setYear(y => y + 1) } else setMonth(m => m + 1)
  }

  const totalRent = leases.reduce((s, l) => s + Number(l.rent_amount), 0)

  async function generate() {
    setLoading(true)
    setError("")
    setResult(null)
    const res = await fetch("/api/rent/generate", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ year, month }),
    })
    const data = await res.json()
    setLoading(false)
    if (!res.ok) { setError(data.error ?? "Something went wrong"); return }
    setResult(data)
  }

  return (
    <div className="space-y-5">
      {/* Month picker */}
      <div className="rounded-2xl border border-white/[0.06] bg-[#16161f] p-5">
        <p className="text-xs font-medium uppercase tracking-wider text-white/30 mb-4">Select Month</p>
        <div className="flex items-center justify-center gap-4">
          <button onClick={prevMonth} className="flex h-9 w-9 items-center justify-center rounded-xl border border-white/[0.08] text-white/40 hover:text-white hover:border-white/20 transition">
            <ChevronLeft className="h-4 w-4" />
          </button>
          <span className="min-w-[180px] text-center text-lg font-bold text-white">
            {monthLabel(year, month)}
          </span>
          <button onClick={nextMonth} className="flex h-9 w-9 items-center justify-center rounded-xl border border-white/[0.08] text-white/40 hover:text-white hover:border-white/20 transition">
            <ChevronRight className="h-4 w-4" />
          </button>
        </div>
      </div>

      {/* Summary */}
      <div className="rounded-2xl border border-white/[0.06] bg-[#16161f] overflow-hidden">
        <div className="px-5 py-4 border-b border-white/[0.06] flex items-center justify-between">
          <div className="flex items-center gap-2">
            <Users className="h-4 w-4 text-indigo-400" />
            <p className="text-sm font-semibold text-white">Active Tenants ({leases.length})</p>
          </div>
          <p className="text-sm font-bold text-emerald-400">{formatCurrency(totalRent)}<span className="text-xs text-white/30">/mo total</span></p>
        </div>

        {leases.length === 0 ? (
          <div className="py-10 text-center text-sm text-white/30">
            No active leases found. Add leases first.
          </div>
        ) : (
          <div className="divide-y divide-white/[0.04]">
            {leases.map((l: any) => (
              <div key={l.id} className="flex items-center justify-between px-5 py-3">
                <div>
                  <p className="text-sm font-medium text-white">
                    {l.tenant?.first_name} {l.tenant?.last_name}
                  </p>
                  <p className="text-xs text-white/35">
                    {l.property?.name}{l.unit ? ` · Unit ${l.unit.unit_number}` : ""}
                  </p>
                </div>
                <p className="text-sm font-semibold text-white">{formatCurrency(l.rent_amount)}</p>
              </div>
            ))}
          </div>
        )}
      </div>

      {/* Result */}
      {result && (
        <div className={`rounded-xl border px-4 py-3 flex items-start gap-3 ${
          result.created > 0
            ? "border-emerald-500/20 bg-emerald-500/5"
            : "border-amber-500/20 bg-amber-500/5"
        }`}>
          <CheckCircle2 className={`h-5 w-5 shrink-0 mt-0.5 ${result.created > 0 ? "text-emerald-400" : "text-amber-400"}`} />
          <div>
            <p className={`text-sm font-semibold ${result.created > 0 ? "text-emerald-400" : "text-amber-400"}`}>
              {result.message}
            </p>
            {result.skipped > 0 && (
              <p className="text-xs text-white/40 mt-0.5">{result.skipped} already existed and were skipped.</p>
            )}
          </div>
        </div>
      )}

      {error && (
        <div className="rounded-xl border border-red-500/20 bg-red-500/5 px-4 py-3 flex items-center gap-2">
          <AlertCircle className="h-4 w-4 text-red-400 shrink-0" />
          <p className="text-sm text-red-400">{error}</p>
        </div>
      )}

      {/* Actions */}
      <div className="flex gap-3">
        <button
          onClick={() => router.push("/rent")}
          className="rounded-xl border border-white/10 px-5 py-2.5 text-sm text-white/50 hover:text-white transition"
        >
          Cancel
        </button>
        <button
          onClick={generate}
          disabled={loading || leases.length === 0}
          className="flex-1 flex items-center justify-center gap-2 rounded-xl bg-indigo-600 px-5 py-2.5 text-sm font-semibold text-white hover:bg-indigo-500 disabled:opacity-50 transition hover:shadow-lg hover:shadow-indigo-500/25"
        >
          {loading ? (
            <span className="animate-pulse">Generating…</span>
          ) : (
            <>
              <Zap className="h-4 w-4" />
              Generate {leases.length} Payment{leases.length !== 1 ? "s" : ""} for {monthLabel(year, month)}
            </>
          )}
        </button>
      </div>

      {(result?.created ?? 0) > 0 && (
        <button
          onClick={() => router.push("/rent")}
          className="w-full text-center text-sm text-indigo-400 hover:text-indigo-300 transition"
        >
          View Rent Tracker →
        </button>
      )}
    </div>
  )
}
