import React, { useState } from 'react';
import { cn } from '../../utils/cn';

export function DataTable({ columns, data, className, getRowClassName, defaultSort, renderExpandedRow, onRowClick }) {
  const [sorting, setSorting] = useState(
    defaultSort || { column: null, direction: 'desc' }
  );
  const [expandedRows, setExpandedRows] = useState(new Set());

  const handleSort = (columnKey) => {
    setSorting(prev => ({
      column: columnKey,
      direction: prev.column === columnKey && prev.direction === 'asc' ? 'desc' : 'asc'
    }));
  };

  const sortedData = [...(data || [])].sort((a, b) => {
    if (!sorting.column) return 0;
    
    const aVal = a[sorting.column];
    const bVal = b[sorting.column];
    
    // Handle null/undefined values
    if (aVal == null && bVal == null) return 0;
    if (aVal == null) return 1;
    if (bVal == null) return -1;
    
    // Handle numeric values
    if (typeof aVal === 'number' && typeof bVal === 'number') {
      const result = aVal - bVal;
      return sorting.direction === 'asc' ? result : -result;
    }
    
    // Handle string values
    const aStr = String(aVal).toLowerCase();
    const bStr = String(bVal).toLowerCase();
    const result = aStr.localeCompare(bStr);
    return sorting.direction === 'asc' ? result : -result;
  });

  if (!data || data.length === 0) {
    return (
      <div className={cn('p-8 text-center text-slate-400', className)}>
        No data available
      </div>
    );
  }

  return (
    <div className={cn('relative overflow-x-auto', className)}>
      <div className="sticky top-0 z-10 bg-slate-900/95 backdrop-blur-sm border-b border-slate-800">
        <table className="w-full border-collapse">
          <thead>
            <tr>
              {columns.map((column) => (
                <th
                  key={column.accessorKey || column.header}
                  className={cn(
                    "px-4 py-3 text-left text-xs font-semibold text-slate-400 uppercase tracking-wider",
                    "bg-slate-900/95 backdrop-blur-sm",
                    column.accessorKey && "cursor-pointer hover:bg-slate-800/50 transition-colors select-none"
                  )}
                  onClick={() => column.accessorKey && handleSort(column.accessorKey)}
                >
                  <div className="flex items-center gap-2">
                    <span>{column.header}</span>
                    {sorting.column === column.accessorKey && (
                      <span className="text-slate-500">
                        {sorting.direction === 'asc' ? '↑' : '↓'}
                      </span>
                    )}
                  </div>
                </th>
              ))}
            </tr>
          </thead>
        </table>
      </div>
      
      <div className="overflow-y-auto max-h-[calc(100vh-400px)]">
        <table className="w-full border-collapse">
          <tbody>
            {sortedData.map((row, rowIndex) => {
              const rowId = row.id || `row-${rowIndex}`;
              const isExpanded = expandedRows.has(rowId);
              
              return (
                <React.Fragment key={rowId}>
                  <tr
                    className={cn(
                      "border-b border-slate-800/30 transition-colors",
                      "hover:bg-slate-800/30 cursor-pointer",
                      rowIndex % 2 === 0 ? "bg-slate-900/20" : "bg-slate-900/10",
                      getRowClassName && getRowClassName(row, rowIndex)
                    )}
                    onClick={(e) => {
                      // Handle expand/collapse on expand icon click
                      if (e.target.closest('td:first-child') && renderExpandedRow) {
                        setExpandedRows(prev => {
                          const next = new Set(prev);
                          if (next.has(rowId)) {
                            next.delete(rowId);
                          } else {
                            next.add(rowId);
                          }
                          return next;
                        });
                      } else if (onRowClick) {
                        // Handle row click for modal
                        onRowClick(row);
                      } else if (renderExpandedRow) {
                        // Fallback to expand/collapse
                        setExpandedRows(prev => {
                          const next = new Set(prev);
                          if (next.has(rowId)) {
                            next.delete(rowId);
                          } else {
                            next.add(rowId);
                          }
                          return next;
                        });
                      }
                    }}
                  >
                    {renderExpandedRow && (
                      <td className="px-2 py-3 w-8">
                        <span className="text-slate-500 text-xs">
                          {isExpanded ? '▼' : '▶'}
                        </span>
                      </td>
                    )}
                    {columns.map((column) => (
                      <td 
                        key={column.accessorKey || column.header} 
                        className="px-4 py-3 text-sm whitespace-nowrap"
                      >
                        {column.cell 
                          ? column.cell({ row: { original: row } })
                          : row[column.accessorKey] || '—'
                        }
                      </td>
                    ))}
                  </tr>
                  {isExpanded && renderExpandedRow && (
                    <tr key={`${rowIndex}-expanded`}>
                      <td colSpan={columns.length + (renderExpandedRow ? 1 : 0)} className="p-0">
                        {renderExpandedRow({ row: { original: row } })}
                      </td>
                    </tr>
                  )}
                </React.Fragment>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}
