import { ReactNode } from "react";
import AdminEmptyState from "./AdminEmptyState";
import type { IconDefinition } from "@fortawesome/fontawesome-svg-core";

export interface AdminDataTableColumn<T> {
  key: string;
  header: string;
  render: (item: T, index: number) => ReactNode;
  width?: string;
  align?: "left" | "right" | "center";
  className?: string;
}

interface AdminDataTableProps<T> {
  items: T[];
  columns: AdminDataTableColumn<T>[];
  rowKey: (item: T, index: number) => string | number;
  actions?: (item: T, index: number) => ReactNode;
  emptyState?: {
    title: string;
    description?: string;
    icon?: IconDefinition;
    action?: { label: string; onClick: () => void };
  };
  className?: string;
}

export default function AdminDataTable<T>({
  items,
  columns,
  rowKey,
  actions,
  emptyState,
  className = "",
}: AdminDataTableProps<T>) {
  if (items.length === 0 && emptyState) {
    return <AdminEmptyState {...emptyState} />;
  }

  const alignClass = {
    left: "text-left",
    right: "text-right",
    center: "text-center",
  };

  return (
    <div className={`overflow-x-auto ${className}`}>
      <table className="w-full text-left text-sm">
        <thead>
          <tr className="border-b border-slate-800 text-xs font-semibold uppercase tracking-wider text-slate-500">
            {columns.map((col) => (
              <th
                key={col.key}
                className={`px-4 py-3 font-semibold ${
                  col.align ? alignClass[col.align] : "text-left"
                } ${col.width ?? ""}`}
              >
                {col.header}
              </th>
            ))}
            {actions && (
              <th className="px-4 py-3 text-right font-semibold">Actions</th>
            )}
          </tr>
        </thead>
        <tbody className="divide-y divide-slate-800">
          {items.map((item, index) => (
            <tr
              key={rowKey(item, index)}
              className="text-slate-200 transition-colors hover:bg-slate-800/40"
            >
              {columns.map((col) => (
                <td
                  key={col.key}
                  className={`px-4 py-3 align-middle ${
                    col.align ? alignClass[col.align] : "text-left"
                  } ${col.className ?? ""}`}
                >
                  {col.render(item, index)}
                </td>
              ))}
              {actions && (
                <td className="px-4 py-3 text-right align-middle">
                  <div className="flex items-center justify-end gap-1">
                    {actions(item, index)}
                  </div>
                </td>
              )}
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}
