import { redirect } from "next/navigation"
import { eq, asc } from "drizzle-orm"
import { db } from "@/lib/db"
import { leases as leasesTable } from "@/lib/db/schema"
import { getSessionUser } from "@/lib/session"
import { getEffectiveOwnerId } from "@/lib/account"
import Link from "next/link"
import { FileText, AlertTriangle, ArrowRight } from "lucide-react"
import { EmptyState } from "@/components/shared/empty-state"
import { formatDate, daysUntil } from "@/lib/utils"
import { cn } from "@/lib/utils"

export const metadata = { title: "Leases" }

const statusColors: Record<string, string> = {
  active:     "text-emerald-400 bg-emerald-500/10 border-emerald-500/20",
  expired:    "text-red-400 bg-red-500/10 border-red-500/20",
  terminated: "text-white/40 bg-white/5 border-white/10",
  renewed:    "text-blue-400 bg-blue-500/10 border-blue-500/20",
}

function DaysChip({ days, status }: { days: number; status: string }) {
  if (status !== "active") return <span className="text-sm text-white/25">—</span>
  if (days <= 0) return <span className="text-xs font-medium text-red-400">Expired</span>
  const color = days <= 7 ? "text-red-400" : days <= 30 ? "text-amber-400" : days <= 60 ? "text-yellow-400" : "text-white/40"
  return (
    <span className={cn("flex items-center gap-1 text-sm font-medium", color)}>
      {days}d
      {days <= 60 && <AlertTriangle className="h-3 w-3" />}
    </span>
  )
}

export default async function LeasesPage() {
  const user = await getSessionUser()
  if (!user) redirect("/login")

  const ownerId = await getEffectiveOwnerId(user.id)

  const leases = await db.query.leases.findMany({
    where: eq(leasesTable.user_id, ownerId),
    with: {
      tenant: { columns: { first_name: true, last_name: true } },
      property: { columns: { name: true } },
      unit: { columns: { unit_number: true } },
    },
    orderBy: asc(leasesTable.lease_end),
  })

  const active   = leases?.filter((l: any) => l.status === "active").length ?? 0
  const expiring = leases?.filter((l: any) => l.status === "active" && daysUntil(l.lease_end) <= 60).length ?? 0
  const expired  = leases?.filter((l: any) => l.status === "expired").length ?? 0

  return (
    <div className="space-y-6">
      {/* Stats */}
      <div className="grid grid-cols-3 gap-3">
        {[
          { label: "Active",             value: active,   color: "text-emerald-400" },
          { label: "Expiring (60 days)", value: expiring, color: "text-amber-400"   },
          { label: "Expired",            value: expired,  color: "text-red-400"     },
        ].map((s) => (
          <div key={s.label} className="rounded-xl border border-white/[0.06] bg-[#16161f] p-4">
            <p className="text-xs text-white/35">{s.label}</p>
            <p className={`mt-1 text-2xl font-bold tabular-nums ${s.color}`}>{s.value}</p>
          </div>
        ))}
      </div>

      {!leases?.length ? (
        <EmptyState
          icon={FileText}
          title="No leases yet"
          description="Add leases to track expiry dates and get automatic reminders."
          action={{ label: "Add lease", href: "/leases/new" }}
        />
      ) : (
        <>
          {/* Desktop table */}
          <div className="hidden md:block rounded-xl border border-white/[0.06] bg-[#16161f] overflow-hidden">
            <table className="w-full">
              <thead>
                <tr className="border-b border-white/[0.06]">
                  {["Tenant", "Property / Unit", "Period", "Rent", "Status", "Ends in", ""].map((h) => (
                    <th key={h} className="px-5 py-3.5 text-left text-xs font-medium text-white/30 tracking-wide">{h}</th>
                  ))}
                </tr>
              </thead>
              <tbody className="divide-y divide-white/[0.04]">
                {leases.map((lease) => {
                  const days = daysUntil(lease.lease_end)
                  const canRenew = (lease.status === "active" && days <= 60) || lease.status === "expired"
                  return (
                    <tr key={lease.id} className="group hover:bg-white/[0.02] transition">
                      <td className="px-5 py-3.5">
                        <Link href={`/leases/${lease.id}`} className="text-sm font-medium text-white hover:text-indigo-300 transition">
                          {lease.tenant?.first_name} {lease.tenant?.last_name}
                        </Link>
                      </td>
                      <td className="px-5 py-3.5">
                        <p className="text-sm text-white/70">{lease.property?.name}</p>
                        <p className="text-xs text-white/35">Unit {lease.unit?.unit_number ?? "—"}</p>
                      </td>
                      <td className="px-5 py-3.5">
                        <p className="text-xs text-white/50">{formatDate(lease.lease_start)}</p>
                        <p className="text-xs text-white/50">→ {formatDate(lease.lease_end)}</p>
                      </td>
                      <td className="px-5 py-3.5">
                        <p className="text-sm font-semibold text-white tabular-nums">${lease.rent_amount}<span className="text-xs text-white/30">/mo</span></p>
                      </td>
                      <td className="px-5 py-3.5">
                        <span className={cn("rounded-md border px-2 py-0.5 text-xs font-medium capitalize", statusColors[lease.status] ?? statusColors.active)}>
                          {lease.status}
                        </span>
                      </td>
                      <td className="px-5 py-3.5">
                        <DaysChip days={days} status={lease.status} />
                      </td>
                      <td className="px-5 py-3.5 text-right">
                        <div className="flex items-center justify-end gap-4">
                          {canRenew && (
                            <Link
                              href={`/leases/new?tenant_id=${lease.tenant_id}&property_id=${lease.property_id}&unit_id=${lease.unit_id ?? ""}&rent_amount=${lease.rent_amount}`}
                              className="inline-flex items-center gap-1 text-xs font-medium text-indigo-400 hover:text-indigo-300 transition"
                            >
                              Renew <ArrowRight className="h-3 w-3" />
                            </Link>
                          )}
                          <Link
                            href={`/leases/${lease.id}`}
                            className="inline-flex items-center gap-1 text-xs font-medium text-white/50 hover:text-white transition"
                          >
                            View <ArrowRight className="h-3 w-3" />
                          </Link>
                        </div>
                      </td>
                    </tr>
                  )
                })}
              </tbody>
            </table>
          </div>

          {/* Mobile cards */}
          <div className="md:hidden space-y-2">
            {leases.map((lease) => {
              const days = daysUntil(lease.lease_end)
              const canRenew = (lease.status === "active" && days <= 60) || lease.status === "expired"
              return (
                <div key={lease.id} className="rounded-xl border border-white/[0.06] bg-[#16161f] p-4 space-y-3">
                  <div className="flex items-start justify-between gap-2">
                    <Link href={`/leases/${lease.id}`} className="min-w-0">
                      <p className="text-sm font-semibold text-white">
                        {lease.tenant?.first_name} {lease.tenant?.last_name}
                      </p>
                      <p className="text-xs text-white/40 mt-0.5">
                        {lease.property?.name} · Unit {lease.unit?.unit_number ?? "—"}
                      </p>
                    </Link>
                    <span className={cn("shrink-0 rounded-md border px-2 py-0.5 text-xs font-medium capitalize", statusColors[lease.status] ?? statusColors.active)}>
                      {lease.status}
                    </span>
                  </div>
                  <div className="flex items-center justify-between text-xs text-white/40">
                    <span>{formatDate(lease.lease_start)} → {formatDate(lease.lease_end)}</span>
                    <span className="font-semibold text-white">${lease.rent_amount}/mo</span>
                  </div>
                  <div className="flex items-center justify-between border-t border-white/[0.04] pt-2">
                    <DaysChip days={days} status={lease.status} />
                    {canRenew && (
                      <Link
                        href={`/leases/new?tenant_id=${lease.tenant_id}&property_id=${lease.property_id}&unit_id=${lease.unit_id ?? ""}&rent_amount=${lease.rent_amount}`}
                        className="text-xs font-medium text-indigo-400 hover:text-indigo-300 transition"
                      >
                        Renew →
                      </Link>
                    )}
                  </div>
                </div>
              )
            })}
          </div>
        </>
      )}
    </div>
  )
}
