import { redirect } from "next/navigation"
import { eq, desc } from "drizzle-orm"
import { db } from "@/lib/db"
import { rent_payments } from "@/lib/db/schema"
import { getSessionUser } from "@/lib/session"
import Link from "next/link"
import { CreditCard, Plus, Upload } from "lucide-react"
import { EmptyState } from "@/components/shared/empty-state"
import { RentTable } from "./rent-table"
import { CsvExportButton } from "@/components/forms/csv-export-button"

export const metadata = { title: "Rent Tracker" }

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

  const payments = await db.query.rent_payments.findMany({
    where: eq(rent_payments.user_id, user.id),
    with: {
      tenant: { columns: { first_name: true, last_name: true } },
      property: { columns: { name: true } },
      unit: { columns: { unit_number: true } },
    },
    orderBy: desc(rent_payments.due_date),
  })

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-lg font-semibold text-white">Rent Tracker</h2>
          <p className="text-sm text-white/40">{payments?.length ?? 0} total records</p>
        </div>
        <div className="flex items-center gap-2">
          <Link href="/rent/import" className="flex items-center gap-2 rounded-lg border border-white/10 px-3 py-2 text-sm text-white/60 hover:border-white/20 hover:text-white transition">
            <Upload className="h-4 w-4" /> Import CSV
          </Link>
          <CsvExportButton endpoint="/api/export/rent" filename="rent-payments.csv" label="Export CSV" />
          <Link href="/rent/new" className="flex items-center gap-2 rounded-lg bg-indigo-600 px-4 py-2 text-sm font-medium text-white hover:bg-indigo-500 transition">
            <Plus className="h-4 w-4" /> Record Payment
          </Link>
        </div>
      </div>

      {!payments?.length ? (
        <EmptyState icon={CreditCard} title="No payments yet" description="Record rent payments to track collections." action={{ label: "Record payment", href: "/rent/new" }} />
      ) : (
        <RentTable payments={payments} />
      )}
    </div>
  )
}
