'use client';

import { ReactNode } from 'react';

export interface Column<T> {
  key: string;
  header: string;
  render?: (item: T) => ReactNode;
  className?: string;
  sortable?: boolean;
}

interface DataTableProps<T> {
  columns: Column<T>[];
  data: T[];
  loading?: boolean;
  selectedIds?: Set<string>;
  onSelect?: (id: string) => void;
  onSelectAll?: () => void;
  getRowId: (item: T) => string;
  showCheckbox?: boolean;
  emptyMessage?: string;
  rowClassName?: string;
  skeletonRows?: number;
  skeletonComponent?: ReactNode;
}

// ✅ Moved outside — accepts props instead of closing over them
interface SkeletonRowProps {
  showCheckbox: boolean;
  columnCount: number;
}

function SkeletonRow({ showCheckbox, columnCount }: SkeletonRowProps) {
  return (
    <tr className="animate-pulse">
      {showCheckbox && (
        <td className="px-4 py-3">
          <div className="w-4 h-4 rounded" style={{ background: 'var(--color-border)' }}></div>
        </td>
      )}
      {Array.from({ length: columnCount }).map((_, i) => (
        <td key={i} className="px-4 py-3">
          <div className="h-4 rounded w-full max-w-50" style={{ background: 'var(--color-border)' }}></div>
        </td>
      ))}
    </tr>
  );
}

interface DefaultSkeletonProps {
  skeletonRows: number;
  showCheckbox: boolean;
  columnCount: number;
}

function DefaultSkeleton({ skeletonRows, showCheckbox, columnCount }: DefaultSkeletonProps) {
  return (
    <>
      {Array.from({ length: skeletonRows }).map((_, index) => (
        <SkeletonRow key={index} showCheckbox={showCheckbox} columnCount={columnCount} />
      ))}
    </>
  );
}

export default function DataTable<T>({
  columns,
  data,
  loading = false,
  selectedIds = new Set(),
  onSelect,
  onSelectAll,
  getRowId,
  showCheckbox = false,
  emptyMessage = 'No data found',
  rowClassName = '',
  skeletonRows = 10,
  skeletonComponent
}: DataTableProps<T>) {

  return (
    <div className="overflow-x-auto rounded-lg border max-w-full" style={{ borderColor: 'var(--color-border)', WebkitOverflowScrolling: 'touch' }}>
      {/* min-w keeps columns from collapsing on phones — the wrapper scrolls sideways instead. */}
      <table className="w-full min-w-[640px] divide-y" style={{ borderColor: 'var(--color-border)' }}>
        <thead style={{ background: 'var(--color-surface-alt)' }}>
          <tr>
            {showCheckbox && (
              <th className="px-4 py-3 w-12">
                <input
                  type="checkbox"
                  checked={selectedIds.size === data.length && data.length > 0}
                  onChange={onSelectAll}
                  className="rounded focus:ring-cta"
                  style={{ accentColor: 'var(--color-cta)' }}
                  disabled={loading}
                />
              </th>
            )}
            {columns.map((column) => (
              <th
                key={column.key}
                className={`px-3 sm:px-4 py-3 text-left text-xs font-medium uppercase tracking-wider whitespace-nowrap ${column.className || ''}`}
                style={{ color: 'var(--color-text-secondary)' }}
              >
                {column.header}
              </th>
            ))}
          </tr>
        </thead>
        <tbody className="divide-y" style={{ borderColor: 'var(--color-border)' }}>
          {loading ? (
            skeletonComponent || (
              // ✅ Now called with explicit props, no closure over render scope
              <DefaultSkeleton
                skeletonRows={skeletonRows}
                showCheckbox={showCheckbox}
                columnCount={columns.length}
              />
            )
          ) : (
            data.map((item) => (
              <tr
                key={getRowId(item)}
                className={`hover:bg-surface-alt transition-colors ${rowClassName}`}
                style={{ background: 'var(--color-surface)' }}
              >
                {showCheckbox && (
                  <td className="px-4 py-3">
                    <input
                      type="checkbox"
                      checked={selectedIds.has(getRowId(item))}
                      onChange={() => onSelect?.(getRowId(item))}
                      className="rounded focus:ring-cta"
                      style={{ accentColor: 'var(--color-cta)' }}
                    />
                  </td>
                )}
                {columns.map((column) => (
                  <td
                    key={column.key}
                    className={`px-3 sm:px-4 py-3 text-sm ${column.className || ''}`}
                    style={{ color: 'var(--color-text)' }}
                  >
                    {/* ✅ Replaced (item as any) with a proper Record type */}
                    {column.render ? column.render(item) : (item as Record<string, ReactNode>)[column.key]}
                  </td>
                ))}
              </tr>
            ))
          )}
        </tbody>
      </table>

      {!loading && data.length === 0 && (
        <div className="text-center py-8" style={{ color: 'var(--color-text-secondary)' }}>
          {emptyMessage}
        </div>
      )}
    </div>
  );
}