import { clsx } from "clsx";

export type Column<T> = {
  key: string;
  header: React.ReactNode;
  cell: (row: T) => React.ReactNode;
  align?: "left" | "right" | "center";
  className?: string;
  width?: string;
};

type Props<T> = {
  columns: Column<T>[];
  rows: T[];
  rowKey: (row: T) => string;
  emptyMessage?: React.ReactNode;
  className?: string;
  onRowHref?: (row: T) => string | undefined;
  dense?: boolean;
};

export function DataTable<T>({
  columns,
  rows,
  rowKey,
  emptyMessage = "No records.",
  className,
  dense,
}: Props<T>) {
  return (
    <div
      className={clsx(
        "overflow-hidden rounded-xl border border-[var(--color-line)] bg-white",
        className,
      )}
    >
      {rows.length === 0 ? (
        <div className="p-6 text-sm text-[var(--color-slate)]">{emptyMessage}</div>
      ) : (
        <div className="overflow-x-auto">
          <table className="w-full text-left text-sm">
            <thead className="border-b border-[var(--color-line)] bg-[var(--color-line)]/25 text-[11px] font-bold uppercase tracking-wider text-[var(--color-slate)]">
              <tr>
                {columns.map((col) => (
                  <th
                    key={col.key}
                    scope="col"
                    style={col.width ? { width: col.width } : undefined}
                    className={clsx(
                      "px-5 py-3",
                      col.align === "right" && "text-right",
                      col.align === "center" && "text-center",
                      col.className,
                    )}
                  >
                    {col.header}
                  </th>
                ))}
              </tr>
            </thead>
            <tbody>
              {rows.map((row, index) => (
                <tr
                  key={rowKey(row)}
                  className={clsx(
                    "border-b border-[var(--color-line)] last:border-b-0 transition-colors hover:bg-[var(--color-mist)]/25",
                    index % 2 === 1 && "bg-[var(--color-line)]/10",
                  )}
                >
                  {columns.map((col) => (
                    <td
                      key={col.key}
                      className={clsx(
                        dense ? "px-5 py-2.5" : "px-5 py-3.5",
                        col.align === "right" && "text-right",
                        col.align === "center" && "text-center",
                        col.className,
                      )}
                    >
                      {col.cell(row)}
                    </td>
                  ))}
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}
