import React, { useMemo, useState, useEffect } from 'react';
import { Edit2, Trash2, Filter, ChevronLeft, ChevronRight, ChevronsLeft, ChevronsRight } from 'lucide-react';
import { cn } from '@/lib/utils';
import AdvancedFiltersModal from './AdvancedFiltersModal';

const ExcelTable = ({ 
    data = [], 
    columns, 
    filterDefs = [], 
    onEdit, 
    onDelete,
    onRowClick, // Handler para clique na linha (usado no CNAB)
    loading = false, 
    pageSize: initialPageSize = 50,
    selectedIds = [],
    onSelectionChange,
    rowKey = 'id',
    // Novas props para edição inline
    editableColumns = [], // Array de field names que são editáveis
    onCellEdit = null, // Callback quando uma célula é editada: (rowId, field, newValue) => void
    pendingEdits = {}, // Objeto com edições pendentes: { [rowId]: { [field]: value } }
    showValidationButton = false, // Mostra botão de validação no rodapé
    onValidateEdits = null // Callback para validar edições pendentes
}) => {
  const [showFilters, setShowFilters] = useState(false);
  const [filters, setFilters] = useState({});
  const [sortConfig, setSortConfig] = useState({ key: null, direction: 'asc' });
  
  // Pagination State
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(initialPageSize);
  
  // Estado para edição inline
  const [editingCell, setEditingCell] = useState(null); // { rowId, field }
  const [editValue, setEditValue] = useState('');

  // 1. Extract Unique Values for filters
  const options = React.useMemo(() => {
    const opts = {};
    if (!data || data.length === 0) return opts;
    
    const getUnique = (key) => [...new Set(data.map(item => item[key]).filter(Boolean))].sort();
    
    filterDefs.forEach(def => {
        if (def.type === 'select') {
            opts[def.field] = getUnique(def.field);
        }
    });

    return opts;
  }, [data, filterDefs]);

  // 2. Process Data (Filter + Sort)
  const processedData = React.useMemo(() => {
    if (!data || data.length === 0) return [];
    let result = [...data];

    // Filter
    Object.keys(filters).forEach(key => {
      if (filters[key]) {
        result = result.filter(item => {
           const itemValue = String(item[key] || '').toLowerCase();
           const filterValue = String(filters[key]).toLowerCase();
           return itemValue.includes(filterValue);
        });
      }
    });

    // Sort
    if (sortConfig.key) {
      result.sort((a, b) => {
        const valA = a[sortConfig.key] || '';
        const valB = b[sortConfig.key] || '';
        
        if (valA < valB) return sortConfig.direction === 'asc' ? -1 : 1;
        if (valA > valB) return sortConfig.direction === 'asc' ? 1 : -1;
        return 0;
      });
    }

    return result;
  }, [data, filters, sortConfig]);

  // 3. Paginate
  const paginatedData = React.useMemo(() => {
    const startIndex = (currentPage - 1) * pageSize;
    return processedData.slice(startIndex, startIndex + pageSize);
  }, [processedData, currentPage, pageSize]);

  // Reset page when filters or pageSize change
  useEffect(() => {
    setCurrentPage(1);
  }, [filters, sortConfig, pageSize]);

  // Selection handlers
  const handleSelectAll = (e) => {
    if (!onSelectionChange) return;
    if (e.target.checked) {
        const allIds = processedData.map(item => item[rowKey]);
        onSelectionChange(allIds);
    } else {
        onSelectionChange([]);
    }
  };

  const handleSelectRow = (id) => {
    if (!onSelectionChange) return;
    const newSelected = selectedIds.includes(id)
      ? selectedIds.filter(x => x !== id)
      : [...selectedIds, id];
    onSelectionChange(newSelected);
  };

  const isAllSelected = processedData && processedData.length > 0 && processedData.every(item => selectedIds.includes(item[rowKey]));
  const isIndeterminate = processedData && processedData.some(item => selectedIds.includes(item[rowKey])) && !isAllSelected;

  const totalPages = Math.ceil(processedData.length / pageSize);

  const handleSort = (key) => {
    setSortConfig(current => ({
      key,
      direction: current.key === key && current.direction === 'asc' ? 'desc' : 'asc'
    }));
  };

  const handleApplyFilters = (newFilters) => {
    setFilters(newFilters);
    setShowFilters(false);
  };

  return (
    <>
      <div className="bg-white dark:bg-[#1b1b1b] border border-slate-200 dark:border-zinc-800 rounded-lg flex flex-col h-full w-full overflow-hidden shadow-xl text-[clamp(0.875rem,1vw,0.9375rem)] font-sans relative">
        
        {/* Loading Overlay */}
        {loading && (
            <div className="absolute inset-0 z-50 bg-white/80 dark:bg-[#1b1b1b]/80 backdrop-blur-sm flex items-center justify-center">
                <div className="flex flex-col items-center gap-4">
                    <div className="relative">
                        <div className="w-12 h-12 border-4 border-slate-200 dark:border-zinc-800 border-t-emerald-500 rounded-full animate-spin"></div>
                        <div className="absolute inset-0 flex items-center justify-center">
                            <div className="w-2 h-2 bg-emerald-500 rounded-full animate-pulse"></div>
                        </div>
                    </div>
                    <span className="text-emerald-500 font-bold uppercase tracking-widest text-[clamp(0.75rem,0.9vw,0.8125rem)] animate-pulse">Carregando Dados...</span>
                </div>
            </div>
        )}

      {/* Top Toolbar */}
      <div className="flex items-center justify-between px-4 py-3 bg-white dark:bg-[#1b1b1b] border-b border-slate-200 dark:border-zinc-800">
        
        {/* Left Actions */}
        <div className="flex items-center gap-3">
            {/* Filter Button */}
            {filterDefs.length > 0 && (
                <button 
                    onClick={() => setShowFilters(true)}
                    className={cn(
                        "flex items-center gap-1.5 px-3 py-1.5 border rounded-lg font-semibold transition-colors",
                        Object.keys(filters).length > 0 
                        ? 'bg-emerald-500/10 border-emerald-500/30 text-emerald-400 hover:bg-emerald-500/20' 
                        : 'bg-slate-200 dark:bg-zinc-800 hover:bg-slate-300 dark:hover:bg-zinc-700 border-slate-300 dark:border-zinc-700 text-slate-700 dark:text-zinc-300'
                    )}
                >
                    <Filter size={14} strokeWidth={2.5} />
                    <span className="uppercase tracking-wide text-[11px]">
                        {Object.keys(filters).length > 0 ? `${Object.keys(filters).length} Filtros` : 'Filtros Avançados'}
                    </span>
                </button>
            )}

            {/* Total Records */}
            <div className="flex items-center gap-2">
                <span className="text-slate-600 dark:text-zinc-400 font-bold uppercase tracking-widest text-[clamp(0.75rem,0.9vw,0.8125rem)]">Total:</span>
                <span className="text-emerald-500 font-mono font-bold">{processedData.length}</span>
            </div>
        </div>

        {/* Right Actions - Delete Selected */}
        {onDelete && selectedIds.length > 0 && (
            <button 
                onClick={() => onDelete(selectedIds)}
                className="flex items-center gap-2 px-3 py-1.5 bg-rose-500/10 text-rose-500 hover:bg-rose-500/20 border border-rose-500/20 rounded-lg transition-colors"
            >
                <Trash2 size={14} />
                <span className="font-bold uppercase tracking-wider text-[clamp(0.75rem,0.9vw,0.8125rem)]">Excluir ({selectedIds.length})</span>
            </button>
        )}
      </div>

      {/* Table Container */}
      <div className="overflow-x-auto overflow-y-auto flex-1 relative custom-scrollbar w-full min-w-0">
        <table className="border-collapse w-full min-w-full">
          <thead className="sticky top-0 z-20 bg-white dark:bg-[#1b1b1b] shadow-lg shadow-black/10 dark:shadow-black/20">
            <tr className="border-b border-slate-200 dark:border-zinc-800">
                {/* Checkbox Header */}
                {onSelectionChange && (
                    <th className="sticky left-0 z-30 bg-white dark:bg-[#1b1b1b] w-[40px] min-w-[40px] h-[40px] border-r border-slate-200 dark:border-zinc-800">
                         <div className="flex items-center justify-center h-full w-full">
                             <input 
                                type="checkbox" 
                                checked={isAllSelected}
                                ref={input => { if (input) input.indeterminate = isIndeterminate; }}
                                onChange={handleSelectAll}
                                className="appearance-none w-3.5 h-3.5 border-2 border-slate-300 dark:border-zinc-600 rounded-sm bg-white dark:bg-[#2a2a2a] checked:bg-emerald-500 checked:border-emerald-500 transition-all cursor-pointer relative checked:bg-[url('data:image/svg+xml;charset=UTF-8,%3Csvg%20width%3D%2214%22%20height%3D%2214%22%20viewBox%3D%220%200%2014%2014%22%20fill%3D%22none%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%3Cpath%20d%3D%22M2.5%207L5.5%2010L11.5%204%22%20stroke%3D%22%23FFF%22%20stroke-width%3D%222%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%2F%3E%3C%2Fsvg%3E')] bg-center bg-no-repeat bg-[length:70%]"
                             />
                         </div>
                    </th>
                )}

               {/* Dynamic Columns */}
               {columns.map((col, idx) => {
                   const isActionColumn = col.field === 'acoes' || col.header === 'Ações';
                   return (
                   <th 
                        key={idx} 
                        onClick={() => !isActionColumn && handleSort(col.field)}
                        className={cn(
                            "h-[40px] border-r border-slate-200 dark:border-zinc-800 bg-white dark:bg-[#1b1b1b] px-3 relative group transition-colors",
                            !isActionColumn && "cursor-pointer hover:bg-slate-50 dark:hover:bg-zinc-800/50"
                        )}
                        style={{ width: col.width, minWidth: col.width }}
                    >
                       <div className="flex items-center justify-between h-full w-full">
                           <span className={cn(
                               "uppercase font-bold tracking-wider text-[clamp(0.75rem,0.9vw,0.8125rem)]",
                               sortConfig.key === col.field ? "text-emerald-500" : "text-slate-600 dark:text-zinc-500 group-hover:text-slate-900 dark:group-hover:text-zinc-300"
                           )}>
                               {col.header}
                           </span>
                           
                           {/* Sort Indicator */}
                           {!isActionColumn && (
                               <div className={cn(
                                   "flex flex-col gap-0.5",
                                   sortConfig.key === col.field ? 'opacity-100' : 'opacity-40 group-hover:opacity-100'
                               )}>
                                    <svg width="8" height="4" viewBox="0 0 8 4" fill="currentColor" className={cn(
                                        "rotate-180",
                                        sortConfig.key === col.field && sortConfig.direction === 'asc' ? 'text-emerald-500' : 'text-slate-500 dark:text-zinc-400'
                                    )}>
                                        <path d="M4 4L0 0H8L4 4Z" />
                                    </svg>
                                    <svg width="8" height="4" viewBox="0 0 8 4" fill="currentColor" className={cn(
                                        sortConfig.key === col.field && sortConfig.direction === 'desc' ? 'text-emerald-500' : 'text-slate-500 dark:text-zinc-400'
                                    )}>
                                        <path d="M4 4L0 0H8L4 4Z" />
                                    </svg>
                               </div>
                           )}
                       </div>
                   </th>
                   );
               })}
            </tr>
          </thead>

          {/* Table Body */}
          <tbody className="bg-white dark:bg-[#151515]">
            {paginatedData.map((row, idx) => (
                <tr 
                    key={row[rowKey] || idx} 
                    onClick={() => onRowClick && onRowClick(row)}
                    className={cn(
                        "h-[44px] border-b border-slate-200 dark:border-zinc-800/50 hover:bg-slate-50 dark:hover:bg-zinc-800/30 transition-colors group text-[clamp(0.875rem,1vw,0.9375rem)]",
                        idx % 2 === 0 ? 'bg-white dark:bg-[#151515]' : 'bg-slate-50 dark:bg-[#181818]',
                        onRowClick && "cursor-pointer"
                    )}
                >
                    
                    {/* Checkbox Cell */}
                    {onSelectionChange && (
                        <td 
                            className={cn(
                                "sticky left-0 z-10 border-r border-slate-200 dark:border-zinc-800 px-0 text-center",
                                idx % 2 === 0 ? 'bg-white dark:bg-[#151515]' : 'bg-slate-50 dark:bg-[#181818]',
                                "group-hover:bg-slate-100 dark:group-hover:bg-zinc-800/30"
                            )}
                            onClick={(e) => e.stopPropagation()}
                        >
                            <div className="flex items-center justify-center h-full w-full">
                                 <input 
                                    type="checkbox" 
                                    checked={selectedIds.includes(row[rowKey])}
                                    onChange={() => handleSelectRow(row[rowKey])}
                                    onClick={(e) => e.stopPropagation()}
                                    className="appearance-none w-3.5 h-3.5 border-2 border-slate-300 dark:border-zinc-600 rounded-sm bg-white dark:bg-[#2a2a2a] checked:bg-emerald-500 checked:border-emerald-500 transition-all cursor-pointer relative checked:bg-[url('data:image/svg+xml;charset=UTF-8,%3Csvg%20width%3D%2214%22%20height%3D%2214%22%20viewBox%3D%220%200%2014%2014%22%20fill%3D%22none%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%3Cpath%20d%3D%22M2.5%207L5.5%2010L11.5%204%22%20stroke%3D%22%23FFF%22%20stroke-width%3D%222%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%2F%3E%3C%2Fsvg%3E')] bg-center bg-no-repeat bg-[length:70%]"
                                 />
                            </div>
                        </td>
                    )}

                    {/* Data Cells */}
                    {columns.map((col, cIdx) => {
                        const isActionColumn = col.field === 'acoes' || col.header === 'Ações';
                        const rowId = row[rowKey];
                        const isSelected = selectedIds.includes(rowId);
                        const isEditable = editableColumns.includes(col.field) && isSelected;
                        const isEditing = editingCell?.rowId === rowId && editingCell?.field === col.field;
                        
                        // Verifica se há edição pendente para este item ou se está em modo de edição em massa
                        // Em edição em massa, se qualquer item selecionado tem edição neste campo, todos mostram
                        const hasPendingEditForThisRow = pendingEdits[rowId] && pendingEdits[rowId][col.field] !== undefined;
                        const hasMassEdit = selectedIds.length > 1 && Object.values(pendingEdits).some(edits => edits[col.field] !== undefined);
                        const hasPendingEdit = hasPendingEditForThisRow || (hasMassEdit && isSelected);
                        
                        // Para edição em massa, pega o valor da primeira edição encontrada
                        let massEditValue = null;
                        if (hasMassEdit && isSelected && !hasPendingEditForThisRow) {
                          const firstEdit = Object.values(pendingEdits).find(edits => edits[col.field] !== undefined);
                          if (firstEdit) {
                            massEditValue = firstEdit[col.field];
                          }
                        }
                        
                        const displayValue = hasPendingEditForThisRow 
                          ? pendingEdits[rowId][col.field] 
                          : (massEditValue !== null ? massEditValue : (row[col.field] || '---'));
                        
                        return (
                        <td 
                            key={cIdx} 
                            className={cn(
                                "border-r border-slate-200 dark:border-zinc-800 px-3 whitespace-nowrap overflow-hidden text-ellipsis relative",
                                isActionColumn ? '' : 'text-slate-700 dark:text-zinc-300',
                                isEditable && !isEditing && "cursor-pointer hover:bg-slate-100 dark:hover:bg-zinc-700/30 hover:ring-1 hover:ring-emerald-500/30",
                                hasPendingEdit && "bg-emerald-500/10 border-l-2 border-l-emerald-500",
                                isEditable && !isEditing && !hasPendingEdit && "group/edit"
                            )}
                            title={isEditable && !isEditing ? "Clique para editar (ou duplo clique)" : ""}
                            style={{ width: col.width, minWidth: col.width }}
                            onClick={(e) => {
                                if (isEditable && !isEditing && onCellEdit) {
                                    e.stopPropagation();
                                    // Para TIPO_CHAVE_PIX, usa o valor original da linha (ID numérico), não o displayValue formatado
                                    const initialValue = col.field === 'TIPO_CHAVE_PIX' 
                                        ? String(row[col.field] || row.tipo_chave_pix || row.tipoPix || '4')
                                        : displayValue;
                                    setEditingCell({ rowId, field: col.field });
                                    setEditValue(initialValue);
                                }
                            }}
                            onDoubleClick={(e) => {
                                if (isEditable && !isEditing && onCellEdit) {
                                    e.stopPropagation();
                                    // Para TIPO_CHAVE_PIX, usa o valor original da linha (ID numérico), não o displayValue formatado
                                    const initialValue = col.field === 'TIPO_CHAVE_PIX' 
                                        ? String(row[col.field] || row.tipo_chave_pix || row.tipoPix || '4')
                                        : displayValue;
                                    setEditingCell({ rowId, field: col.field });
                                    setEditValue(initialValue);
                                }
                            }}
                        >
                             {isEditing ? (
                                 col.field === 'TIPO_CHAVE_PIX' ? (
                                     <select
                                         value={String(editValue || '4')}
                                         onChange={(e) => {
                                             const newValue = e.target.value;
                                             if (onCellEdit) {
                                                 // Compara com o valor original (pode ser número ou string)
                                                 const originalValue = String(row[col.field] || displayValue || '4');
                                                 if (newValue !== originalValue) {
                                                     onCellEdit(rowId, col.field, newValue);
                                                 }
                                             }
                                             setEditingCell(null);
                                             setEditValue('');
                                         }}
                                         onBlur={() => {
                                             setEditingCell(null);
                                             setEditValue('');
                                         }}
                                         onKeyDown={(e) => {
                                             if (e.key === 'Escape') {
                                                 setEditingCell(null);
                                                 setEditValue('');
                                             }
                                         }}
                                         autoFocus
                                         className="w-full px-2 py-1 bg-slate-50 dark:bg-zinc-900 border-2 border-emerald-500 text-slate-900 dark:text-white text-[clamp(0.875rem,1vw,0.9375rem)] rounded focus:outline-none focus:ring-2 focus:ring-emerald-500/50"
                                         onClick={(e) => e.stopPropagation()}
                                     >
                                         <option value="1">Telefone</option>
                                         <option value="2">E-mail</option>
                                         <option value="3">CPF/CNPJ</option>
                                         <option value="4">Chave Aleatória</option>
                                         <option value="5">Dados bancários</option>
                                     </select>
                                 ) : (
                                     <input
                                         type="text"
                                         value={editValue}
                                         onChange={(e) => setEditValue(e.target.value)}
                                         onBlur={() => {
                                             if (onCellEdit && editValue !== displayValue) {
                                                 onCellEdit(rowId, col.field, editValue);
                                             }
                                             setEditingCell(null);
                                             setEditValue('');
                                         }}
                                         onKeyDown={(e) => {
                                             if (e.key === 'Enter') {
                                                 if (onCellEdit && editValue !== displayValue) {
                                                     onCellEdit(rowId, col.field, editValue);
                                                 }
                                                 setEditingCell(null);
                                                 setEditValue('');
                                             } else if (e.key === 'Escape') {
                                                 setEditingCell(null);
                                                 setEditValue('');
                                             }
                                         }}
                                         autoFocus
                                         className="w-full px-2 py-1 bg-slate-50 dark:bg-zinc-900 border-2 border-emerald-500 text-slate-900 dark:text-white text-[clamp(0.875rem,1vw,0.9375rem)] rounded focus:outline-none focus:ring-2 focus:ring-emerald-500/50"
                                         onClick={(e) => e.stopPropagation()}
                                     />
                                 )
                             ) : (
                                 <div className="relative w-full">
                                     {isEditable && !isEditing && (
                                         <div className="absolute -top-1 -right-1 w-2 h-2 bg-emerald-500 rounded-full opacity-0 group-hover/edit:opacity-100 transition-opacity" title="Célula editável" />
                                     )}
                                     {col.render ? (
                                         <div className={cn(
                                             hasPendingEdit && "text-emerald-400 font-semibold",
                                             isEditable && !isEditing && "group-hover/edit:text-emerald-300"
                                         )}>
                                             {col.render({ ...row, [col.field]: displayValue })}
                                         </div>
                                     ) : (
                                         <span className={cn(
                                             hasPendingEdit && "text-emerald-400 font-semibold",
                                             isEditable && !isEditing && "group-hover/edit:text-emerald-300"
                                         )}>
                                             {displayValue}
                                         </span>
                                     )}
                                 </div>
                             )}
                        </td>
                        );
                    })}
                </tr>
            ))}
             {/* Empty State */}
             {!loading && paginatedData.length === 0 && (
                 <tr>
                    <td colSpan={columns.length + (onSelectionChange ? 1 : 0)} className="h-24 text-center text-slate-500 dark:text-zinc-600 italic">
                        {Object.keys(filters).length > 0 ? 'Nenhum registro encontrado para os filtros selecionados.' : 'Nenhum registro disponível.'}
                    </td>
                 </tr>
             )}
          </tbody>
        </table>
      </div>

      {/* Footer com Validação e Paginação */}
      <div className="bg-white dark:bg-[#1b1b1b] border-t border-slate-200 dark:border-zinc-800 flex flex-col overflow-hidden select-none">
        {/* Botão de Validação (quando houver edições pendentes) */}
        {showValidationButton && onValidateEdits && Object.keys(pendingEdits).length > 0 && (
          <div className="px-4 py-3 bg-emerald-500/10 border-b border-emerald-500/20 flex items-center justify-between">
            <div className="flex items-center gap-2">
              <span className="text-emerald-400 text-[clamp(0.75rem,0.9vw,0.8125rem)] font-bold uppercase tracking-wider">
                {Object.keys(pendingEdits).length} item(ns) com edições pendentes
              </span>
            </div>
            <div className="flex items-center gap-2">
              <button
                onClick={() => {
                  if (onValidateEdits) {
                    onValidateEdits();
                  }
                }}
                className="px-4 py-2 bg-emerald-600 hover:bg-emerald-500 text-white rounded-lg text-[clamp(0.75rem,0.9vw,0.8125rem)] font-bold uppercase tracking-wider transition-all shadow-lg shadow-emerald-900/20"
              >
                Validar Edições
              </button>
              <button
                onClick={() => {
                  if (onValidateEdits) {
                    onValidateEdits({ clear: true });
                  }
                }}
                className="px-4 py-2 bg-slate-200 dark:bg-zinc-800 hover:bg-slate-300 dark:hover:bg-zinc-700 text-slate-700 dark:text-zinc-300 rounded-lg text-[clamp(0.75rem,0.9vw,0.8125rem)] font-bold uppercase tracking-wider transition-all"
              >
                Cancelar
              </button>
            </div>
          </div>
        )}
        
        {/* Paginação */}
        <div className="h-[40px] flex items-center justify-between px-4">
            
            {/* Left: Totals */}
            <div className="flex h-full items-center gap-4">
                 <div className="flex items-center gap-2 px-4 h-full relative group min-w-[120px]">
                    <div className="absolute left-0 top-2 bottom-2 w-[3px] bg-emerald-500 rounded-r-sm"></div>
                    <span className="text-[clamp(0.75rem,0.9vw,0.8125rem)] uppercase font-bold text-slate-600 dark:text-zinc-500 tracking-wider">Total:</span>
                    <span className="text-[clamp(0.875rem,1vw,0.9375rem)] font-bold text-slate-900 dark:text-white">{processedData.length}</span>
                    
                    <div className="absolute right-0 top-2 bottom-2 w-[1px] bg-slate-200 dark:bg-zinc-800"></div>
                 </div>

                 <div className="flex items-center gap-2 px-4 h-full relative group min-w-[100px]">
                    <div className="absolute left-0 top-2 bottom-2 w-[3px] bg-emerald-500 rounded-r-sm opacity-0 group-hover:opacity-100 transition-opacity"></div>
                    <span className="text-[clamp(0.75rem,0.9vw,0.8125rem)] uppercase font-bold text-slate-600 dark:text-zinc-500 tracking-wider">Página:</span>
                    <span className="text-[clamp(0.875rem,1vw,0.9375rem)] font-bold text-slate-900 dark:text-white">{currentPage} / {totalPages || 1}</span>
                 </div>
            </div>

            {/* Right: Pagination Controls */}
            <div className="flex items-center gap-1 pr-2">
                 <div className="text-[11px] text-slate-600 dark:text-zinc-500 mr-3 hidden md:block">
                    Exibindo <span className="font-bold text-slate-900 dark:text-zinc-300">{Math.min((currentPage - 1) * pageSize + 1, processedData.length)} a {Math.min(currentPage * pageSize, processedData.length)}</span>
                 </div>

                {/* First Page */}
                <button 
                  onClick={() => setCurrentPage(1)}
                  disabled={currentPage === 1}
                  className="w-7 h-7 flex items-center justify-center rounded bg-slate-50 dark:bg-[#151515] border border-slate-200 dark:border-zinc-800 hover:border-emerald-500 text-slate-600 dark:text-zinc-400 disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
                >
                     <ChevronsLeft size={14} />
                </button>

                {/* Prev Page */}
                <button 
                  onClick={() => setCurrentPage(p => Math.max(1, p - 1))}
                  disabled={currentPage === 1}
                  className="w-7 h-7 flex items-center justify-center rounded bg-slate-50 dark:bg-[#151515] border border-slate-200 dark:border-zinc-800 hover:border-emerald-500 text-slate-600 dark:text-zinc-400 disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
                >
                     <ChevronLeft size={14} />
                </button>
                
                {/* Current Page */}
                <div className="flex gap-1 mx-1">
                    <button className="w-7 h-7 flex items-center justify-center rounded bg-emerald-500 text-white font-bold text-[11px] transition-colors shadow-lg shadow-emerald-500/10">
                        {currentPage}
                    </button>
                </div>

                {/* Next Page */}
                 <button 
                  onClick={() => setCurrentPage(p => Math.min(totalPages, p + 1))}
                  disabled={currentPage === totalPages || totalPages === 0}
                  className="w-7 h-7 flex items-center justify-center rounded bg-slate-50 dark:bg-[#151515] border border-slate-200 dark:border-zinc-800 hover:border-emerald-500 text-slate-600 dark:text-zinc-400 disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
                >
                     <ChevronRight size={14} />
                </button>

                {/* Last Page */}
                 <button 
                  onClick={() => setCurrentPage(totalPages)}
                  disabled={currentPage === totalPages || totalPages === 0}
                  className="w-7 h-7 flex items-center justify-center rounded bg-slate-50 dark:bg-[#151515] border border-slate-200 dark:border-zinc-800 hover:border-emerald-500 text-slate-600 dark:text-zinc-400 disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
                >
                    <ChevronsRight size={14} />
                </button>
            </div>
        </div>
      </div>
      </div>

      <AdvancedFiltersModal 
        isOpen={showFilters} 
        onClose={() => setShowFilters(false)} 
        onApply={handleApplyFilters}
        options={options}
        initialFilters={filters}
        config={filterDefs}
      />
    </>
  );
};

export default ExcelTable;
