import React from "react";

/**
 * columns: Array<{ key: string, label: string, render?: (row) => ReactNode }>
 * data: Array<any>
 * loading: boolean
 * empty: string | ReactNode
 * actions: (row) => ReactNode (optional)
 * onRowClick: (row, event) => void (optional)
 */
const DynamicTable = ({
  columns,
  data,
  loading,
  empty,
  actions,
  onRowClick,
}) => {
  return (
    <div className="overflow-x-auto">
      <table className="min-w-full divide-y divide-gray-100">
        <thead className="bg-gray-100">
          <tr>
            {actions && (
              <th className="px-6 py-3 text-left text-xs font-semibold text-gray-400 capitalize tracking-wider">
                Actions
              </th>
            )}
            {columns.map((col) => (
              <th
                key={col.key}
                className="px-6 py-3 text-left text-xs font-semibold text-gray-400 capitalize tracking-wider"
              >
                {col.label}
              </th>
            ))}
          </tr>
        </thead>
        <tbody className="bg-white divide-y divide-gray-200">
          {loading ? (
            <tr>
              <td
                colSpan={columns.length + (actions ? 1 : 0)}
                className="px-6 py-4 text-center text-gray-500"
              >
                Loading...
              </td>
            </tr>
          ) : data.length === 0 ? (
            <tr>
              <td
                colSpan={columns.length + (actions ? 1 : 0)}
                className="px-6 py-4 text-center text-gray-500"
              >
                {empty || "No data found."}
              </td>
            </tr>
          ) : (
            data.map((row, idx) => (
              <tr
                key={row.id || idx}
                className={`hover:bg-gray-50${
                  onRowClick ? " cursor-pointer" : ""
                }`}
                onClick={onRowClick ? (e) => onRowClick(row, e) : undefined}
              >
                {actions && (
                  <td className="px-6 py-4 whitespace-nowrap text-right text-xs font-medium">
                    {actions(row)}
                  </td>
                )}
                {columns.map((col) => (
                  <td
                    key={col.key}
                    className="px-6 py-4 text-xs font-medium whitespace-nowrap"
                  >
                    {col.render ? col.render(row) : row[col.key]}
                  </td>
                ))}
              </tr>
            ))
          )}
        </tbody>
      </table>
    </div>
  );
};

export default DynamicTable;
