import React from 'react';
import Skeleton from './Skeleton';
import EmptyState from './EmptyState';

/**
 * DataTable — the modern-baseline table.
 *
 * <DataTable
 *   columns={[
 *     { key: 'url', label: 'URL' },
 *     { key: 'status', label: 'Status', align: 'center', render: (row) => <Badge>{row.status}</Badge> },
 *   ]}
 *   rows={rows}
 *   rowKey={(row) => row.id}
 *   loading={isLoading}
 *   empty={{ title: 'No broken links', description: 'Everything resolves cleanly.' }}
 * />
 */
const DataTable = ({
  columns = [],
  rows = [],
  rowKey = (row, index) => row?.id ?? index,
  loading = false,
  empty = null,
  className = '',
}) => {
  if (loading) {
    return (
      <div className={`pr:bg-white pr:rounded-2xl pr:shadow-xs pr:border pr:border-slate-200 pr:p-5 pr:space-y-3 ${className}`}>
        <Skeleton className="pr:h-5 pr:w-1/3" />
        <Skeleton className="pr:h-10 pr:w-full" />
        <Skeleton className="pr:h-10 pr:w-full" />
        <Skeleton className="pr:h-10 pr:w-full" />
      </div>
    );
  }

  if (!rows.length) {
    return empty ? <EmptyState {...empty} className={className} /> : null;
  }

  const alignClass = (align) =>
    align === 'center' ? 'pr:text-center' : align === 'right' ? 'pr:text-right' : 'pr:text-left';

  return (
    <div className={`pr:overflow-hidden pr:rounded-2xl pr:shadow-xs pr:border pr:border-slate-200 pr:bg-white ${className}`}>
      <div className="pr:overflow-x-auto">
        <table className="pr:w-full pr:text-sm">
          <thead>
            <tr className="pr:border-b pr:border-slate-200 pr:bg-slate-50/70">
              {columns.map((col) => (
                <th
                  key={col.key}
                  scope="col"
                  className={`pr:px-4 pr:py-3 pr:text-xs pr:font-semibold pr:uppercase pr:tracking-wide pr:text-slate-500 ${alignClass(col.align)}`}
                >
                  {col.label}
                </th>
              ))}
            </tr>
          </thead>
          <tbody className="pr:divide-y pr:divide-slate-100">
            {rows.map((row, index) => (
              <tr key={rowKey(row, index)} className="pr:hover:bg-slate-50/60">
                {columns.map((col) => (
                  <td key={col.key} className={`pr:px-4 pr:py-3 pr:text-slate-700 ${alignClass(col.align)}`}>
                    {typeof col.render === 'function' ? col.render(row, index) : row?.[col.key]}
                  </td>
                ))}
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
};

export default DataTable;
