import { PageHeader } from "@/components/layout/page-header";
import { Card } from "@/components/ui/card";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { ExportButtons } from "@/components/reports/export-buttons";
import type { ReportColumn } from "@/lib/types";

type Row = Record<string, unknown>;

/**
 * Reusable report shell: a titled, exportable (Excel + PDF) data table.
 * Report pages just compute `columns` + `rows` and render this. Optional
 * `filters` slot renders above the table (e.g. a date-range form).
 */
export function ReportTable({
  title,
  breadcrumb,
  columns,
  rows,
  filters,
  footerNote,
}: {
  title: string;
  breadcrumb?: string;
  columns: ReportColumn[];
  rows: Row[];
  filters?: React.ReactNode;
  footerNote?: string;
}) {
  return (
    <div>
      <PageHeader
        title={title}
        breadcrumb={breadcrumb}
        action={<ExportButtons title={title} columns={columns} rows={rows} />}
      />
      {filters}
      <Card className="mt-4 p-0">
        <div className="overflow-x-auto">
          <Table>
            <TableHeader>
              <TableRow>
                {columns.map((c) => (
                  <TableHead key={c.key} className={c.numeric ? "text-right" : ""}>
                    {c.label}
                  </TableHead>
                ))}
              </TableRow>
            </TableHeader>
            <TableBody>
              {rows.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={columns.length} className="py-10 text-center text-muted-foreground">
                    No data for the selected range.
                  </TableCell>
                </TableRow>
              ) : (
                rows.map((r, i) => (
                  <TableRow key={i}>
                    {columns.map((c) => (
                      <TableCell key={c.key} className={c.numeric ? "text-right tabular-nums" : ""}>
                        {format(r[c.key])}
                      </TableCell>
                    ))}
                  </TableRow>
                ))
              )}
            </TableBody>
          </Table>
        </div>
      </Card>
      <div className="mt-3 flex items-center justify-between text-sm text-muted-foreground">
        <span>Total Records: {rows.length}</span>
        {footerNote && <span>{footerNote}</span>}
      </div>
    </div>
  );
}

function format(v: unknown): string {
  if (v === null || v === undefined) return "—";
  return String(v);
}
