"use client"

import { useState } from "react"
import { ChevronLeft, ChevronRight, CreditCard, FileText } from "lucide-react"
import { cn, formatCurrency } from "@/lib/utils"

const DAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
const MONTHS = ["January","February","March","April","May","June","July","August","September","October","November","December"]

interface CalendarClientProps {
  payments: any[]
  leases: any[]
}

export function CalendarClient({ payments, leases }: CalendarClientProps) {
  const today = new Date()
  const [year, setYear] = useState(today.getFullYear())
  const [month, setMonth] = useState(today.getMonth())
  const [selected, setSelected] = useState<string | null>(null)

  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)
  }

  // Build calendar grid
  const firstDay = new Date(year, month, 1).getDay()
  const daysInMonth = new Date(year, month + 1, 0).getDate()
  const cells: (number | null)[] = [
    ...Array(firstDay).fill(null),
    ...Array.from({ length: daysInMonth }, (_, i) => i + 1),
  ]
  // Pad to complete last row
  while (cells.length % 7 !== 0) cells.push(null)

  function dateKey(day: number) {
    return `${year}-${String(month + 1).padStart(2, "0")}-${String(day).padStart(2, "0")}`
  }

  // Group events by date
  const eventsByDate: Record<string, { type: "payment" | "lease"; item: any }[]> = {}

  for (const p of payments) {
    const key = p.due_date?.slice(0, 10)
    if (!key) continue
    if (!eventsByDate[key]) eventsByDate[key] = []
    eventsByDate[key].push({ type: "payment", item: p })
  }

  for (const l of leases) {
    const key = l.lease_end?.slice(0, 10)
    if (!key) continue
    if (!eventsByDate[key]) eventsByDate[key] = []
    eventsByDate[key].push({ type: "lease", item: l })
  }

  const selectedEvents = selected ? (eventsByDate[selected] ?? []) : []

  const todayKey = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, "0")}-${String(today.getDate()).padStart(2, "0")}`

  return (
    <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
      {/* Calendar grid */}
      <div className="lg:col-span-2 rounded-2xl border border-white/[0.06] bg-[#16161f] overflow-hidden">
        {/* Month nav */}
        <div className="flex items-center justify-between border-b border-white/[0.06] px-5 py-4">
          <button onClick={prevMonth} className="rounded-lg p-1.5 text-white/40 hover:text-white transition hover:bg-white/[0.05]">
            <ChevronLeft className="h-4 w-4" />
          </button>
          <h3 className="text-sm font-semibold text-white">{MONTHS[month]} {year}</h3>
          <button onClick={nextMonth} className="rounded-lg p-1.5 text-white/40 hover:text-white transition hover:bg-white/[0.05]">
            <ChevronRight className="h-4 w-4" />
          </button>
        </div>

        {/* Day headers */}
        <div className="grid grid-cols-7 border-b border-white/[0.04]">
          {DAYS.map((d) => (
            <div key={d} className="py-2 text-center text-[10px] font-semibold uppercase tracking-wider text-white/25">
              {d}
            </div>
          ))}
        </div>

        {/* Days */}
        <div className="grid grid-cols-7">
          {cells.map((day, i) => {
            const key = day ? dateKey(day) : null
            const events = key ? (eventsByDate[key] ?? []) : []
            const isToday = key === todayKey
            const isSelected = key === selected
            const paymentEvents = events.filter((e) => e.type === "payment")
            const leaseEvents = events.filter((e) => e.type === "lease")

            return (
              <div
                key={i}
                onClick={() => day && key && setSelected(isSelected ? null : key)}
                className={cn(
                  "relative min-h-[72px] border-b border-r border-white/[0.03] p-1.5 transition-colors",
                  day ? "cursor-pointer hover:bg-white/[0.03]" : "opacity-0 pointer-events-none",
                  isSelected && "bg-indigo-600/10 border-indigo-500/20",
                )}
              >
                {day && (
                  <>
                    <span className={cn(
                      "flex h-6 w-6 items-center justify-center rounded-full text-xs font-medium",
                      isToday ? "bg-indigo-600 text-white font-bold" : "text-white/50"
                    )}>
                      {day}
                    </span>
                    <div className="mt-1 space-y-0.5">
                      {paymentEvents.slice(0, 2).map((e, j) => (
                        <div key={j} className={cn(
                          "truncate rounded px-1 py-0.5 text-[9px] font-medium",
                          e.item.status === "paid"
                            ? "bg-emerald-500/15 text-emerald-400"
                            : e.item.status === "overdue"
                            ? "bg-red-500/15 text-red-400"
                            : "bg-indigo-500/15 text-indigo-400"
                        )}>
                          {e.item.tenant?.first_name} {formatCurrency(e.item.amount)}
                        </div>
                      ))}
                      {leaseEvents.slice(0, 1).map((e, j) => (
                        <div key={j} className="truncate rounded bg-amber-500/15 px-1 py-0.5 text-[9px] font-medium text-amber-400">
                          Lease ends: {e.item.tenant?.first_name}
                        </div>
                      ))}
                      {events.length > 3 && (
                        <div className="text-[9px] text-white/30 px-1">+{events.length - 3} more</div>
                      )}
                    </div>
                  </>
                )}
              </div>
            )
          })}
        </div>
      </div>

      {/* Side panel */}
      <div className="rounded-2xl border border-white/[0.06] bg-[#16161f] overflow-hidden">
        <div className="border-b border-white/[0.06] px-5 py-4">
          <h3 className="text-sm font-semibold text-white">
            {selected ? new Date(selected + "T12:00:00").toLocaleDateString("en-US", { weekday: "long", month: "long", day: "numeric" }) : "Select a date"}
          </h3>
        </div>

        {!selected ? (
          <div className="flex flex-col items-center justify-center py-16 text-center px-4">
            <p className="text-sm text-white/30">Click any day to see events</p>
          </div>
        ) : selectedEvents.length === 0 ? (
          <div className="flex flex-col items-center justify-center py-16 text-center px-4">
            <p className="text-sm text-white/30">No events this day</p>
          </div>
        ) : (
          <div className="divide-y divide-white/[0.04] p-3 space-y-1">
            {selectedEvents.map((e, i) => (
              <div key={i} className={cn(
                "flex items-start gap-3 rounded-xl p-3",
                e.type === "payment" ? "bg-indigo-500/5" : "bg-amber-500/5"
              )}>
                <div className={cn(
                  "flex h-7 w-7 shrink-0 items-center justify-center rounded-lg border",
                  e.type === "payment"
                    ? "border-indigo-500/20 bg-indigo-500/10 text-indigo-400"
                    : "border-amber-500/20 bg-amber-500/10 text-amber-400"
                )}>
                  {e.type === "payment" ? <CreditCard className="h-3.5 w-3.5" /> : <FileText className="h-3.5 w-3.5" />}
                </div>
                <div className="flex-1 min-w-0">
                  {e.type === "payment" ? (
                    <>
                      <p className="text-xs font-semibold text-white">{e.item.tenant?.first_name} {e.item.tenant?.last_name}</p>
                      <p className="text-xs text-white/40">{formatCurrency(e.item.amount)} due</p>
                      <span className={cn(
                        "mt-1 inline-block rounded-full px-2 py-0.5 text-[10px] font-medium capitalize",
                        e.item.status === "paid" ? "bg-emerald-500/15 text-emerald-400" :
                        e.item.status === "overdue" ? "bg-red-500/15 text-red-400" :
                        "bg-white/10 text-white/40"
                      )}>
                        {e.item.status}
                      </span>
                    </>
                  ) : (
                    <>
                      <p className="text-xs font-semibold text-white">Lease Expiry</p>
                      <p className="text-xs text-white/40">{e.item.tenant?.first_name} {e.item.tenant?.last_name}</p>
                      <p className="text-xs text-white/30">{e.item.property?.name}</p>
                    </>
                  )}
                </div>
              </div>
            ))}
          </div>
        )}

        {/* Legend */}
        <div className="border-t border-white/[0.06] px-5 py-3 space-y-1.5">
          <p className="text-[10px] font-semibold uppercase tracking-wider text-white/20 mb-2">Legend</p>
          {[
            { color: "bg-indigo-500/20 text-indigo-400", label: "Rent pending" },
            { color: "bg-emerald-500/20 text-emerald-400", label: "Rent paid" },
            { color: "bg-red-500/20 text-red-400", label: "Rent overdue" },
            { color: "bg-amber-500/20 text-amber-400", label: "Lease expiry" },
          ].map((l) => (
            <div key={l.label} className="flex items-center gap-2">
              <div className={cn("h-2 w-2 rounded-full", l.color)} />
              <span className="text-xs text-white/40">{l.label}</span>
            </div>
          ))}
        </div>
      </div>
    </div>
  )
}
