import type { ReactNode } from "react";
import { EmptyState } from "@/components/ui/EmptyState";
import { cn } from "@/lib/cn";

export type AdminTableColumn<T> = {
  key: string;
  header: string;
  className?: string;
  headerClassName?: string;
  cell: (row: T) => ReactNode;
};

export function AdminDataTable<T extends { id: number | string }>({
  columns,
  rows,
  emptyTitle = "No results found",
  emptyDescription,
  caption,
}: {
  columns: AdminTableColumn<T>[];
  rows: T[];
  emptyTitle?: string;
  emptyDescription?: string;
  /** Optional accessible table caption for screen readers. */
  caption?: string;
}) {
  if (rows.length === 0) {
    return (
      <EmptyState
        title={emptyTitle}
        description={emptyDescription}
        variant="dashed"
        className="rounded-[10px] border-line/80 shadow-pv"
      />
    );
  }

  return (
    <div className="overflow-x-auto rounded-[10px] border border-line/80 bg-surface shadow-pv">
      <table className="min-w-full border-collapse text-left">
        {caption ? <caption className="sr-only">{caption}</caption> : null}
        <thead>
          <tr className="border-b border-line/80 bg-[#FAFBFC]">
            {columns.map((column) => (
              <th
                key={column.key}
                scope="col"
                className={cn(
                  "whitespace-nowrap px-4 py-3 text-[0.6875rem] font-medium uppercase tracking-[0.06em] text-ink-40",
                  column.headerClassName,
                  column.className,
                )}
              >
                {column.header}
              </th>
            ))}
          </tr>
        </thead>
        <tbody>
          {rows.map((row) => (
            <tr
              key={row.id}
              className="border-b border-line/80 transition-colors last:border-b-0 hover:bg-primary/[0.015]"
            >
              {columns.map((column) => (
                <td
                  key={column.key}
                  className={cn(
                    "px-4 py-3.5 align-middle text-[0.8125rem] text-text",
                    column.className,
                  )}
                >
                  {column.cell(row)}
                </td>
              ))}
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}
