import { redirect } from "next/navigation"
import { and, eq, desc } from "drizzle-orm"
import { db } from "@/lib/db"
import { tenants as tenantsTable } from "@/lib/db/schema"
import { getSessionUser } from "@/lib/session"
import { getEffectiveOwnerId } from "@/lib/account"
import { Users, Plus } from "lucide-react"
import { EmptyState } from "@/components/shared/empty-state"
import Link from "next/link"
import { TenantsTable } from "./tenants-table"
import { CsvExportButton } from "@/components/forms/csv-export-button"

export const metadata = { title: "Tenants" }

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

  const ownerId = await getEffectiveOwnerId(user.id)

  const tenants = await db.query.tenants.findMany({
    where: and(eq(tenantsTable.user_id, ownerId), eq(tenantsTable.status, "active")),
    with: {
      unit: { columns: { unit_number: true, rent_amount: true } },
      property: { columns: { name: true } },
    },
    orderBy: desc(tenantsTable.created_at),
  })

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-lg font-semibold text-white">Tenants</h2>
          <p className="text-sm text-white/40">{tenants?.length ?? 0} active tenants</p>
        </div>
        <div className="flex items-center gap-2">
          <CsvExportButton endpoint="/api/export/tenants" filename="tenants.csv" label="Export CSV" />
          <Link
            href="/tenants/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" /> Add Tenant
          </Link>
        </div>
      </div>

      {!tenants?.length ? (
        <EmptyState
          icon={Users}
          title="No tenants yet"
          description="Add tenants and assign them to units to start tracking rent and maintenance."
          action={{ label: "Add tenant", href: "/tenants/new" }}
        />
      ) : (
        <TenantsTable tenants={tenants} />
      )}
    </div>
  )
}
