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

const ExcelTable = ({ 
    data, 
    columns, 
    filterDefs = [], 
    onEdit, 
    onDelete,
    loading = false, 
    pageSize: initialPageSize = 50,
    selectedIds = [],
    onSelectionChange,
    onRowClick,
    rowKey = 'id'
}) => {
  const [showFilters, setShowFilters] = useState(false);
  const [filters, setFilters] = useState({});
  const [sortConfig, setSortConfig] = useState({ key: null, direction: 'asc' });
  
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(initialPageSize);

  const options = React.useMemo(() => {
    const opts = {};
    const getUnique = (key) => [...new Set(data.filter(item => item && item[key]).map(item => item[key]))].sort();
    
    filterDefs.forEach(def => {
        if (def.type === 'select') {
            opts[def.field] = getUnique(def.field);
        }
    });

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

  const processedData = React.useMemo(() => {
    let result = Array.isArray(data) ? [...data] : [];

    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);
        });
      }
    });

    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]);

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

  useEffect(() => {
    setCurrentPage(1);
  }, [filters, sortConfig, pageSize]);

  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/90 dark:bg-[#1b1b1b]/90 backdrop-blur-sm border border-slate-200/60 dark:border-[#2a2a2a]/60 rounded-2xl flex flex-col h-full w-full max-w-full min-w-0 text-xs font-sans antialiased text-slate-700 dark:text-[#e0e0e0] relative overflow-hidden transition-all duration-300 shadow-inner">
        
        {loading && (
            <div className="absolute inset-0 z-50 bg-white/90 dark:bg-[#1b1b1b]/90 backdrop-blur-md flex items-center justify-center">
                <div className="flex flex-col items-center gap-5">
                    <div className="relative">
                        <div className="w-14 h-14 border-4 border-slate-200/50 dark:border-[#252525]/50 border-t-emerald-500 rounded-full animate-spin shadow-lg"></div>
                        <div className="absolute inset-0 w-14 h-14 border-4 border-transparent border-r-emerald-400/50 rounded-full animate-spin" style={{ animationDirection: 'reverse', animationDuration: '0.8s' }}></div>
                    </div>
                    <span className="text-emerald-500 font-bold uppercase tracking-widest text-[11px] drop-shadow-sm">Carregando Dados...</span>
                </div>
            </div>
        )}

      {/* Enhanced Toolbar */}
      <div className="flex items-center justify-between px-4 py-3 bg-gradient-to-r from-slate-50/80 via-white/50 to-slate-50/80 dark:from-[#1b1b1b]/80 dark:via-zinc-900/50 dark:to-[#1b1b1b]/80 backdrop-blur-sm border-b border-slate-200/60 dark:border-[#2a2a2a]/60">
        <div className="flex items-center gap-3">
            <button 
                onClick={() => setShowFilters(true)}
                className={`flex items-center gap-2 px-4 py-2 border rounded-xl font-semibold transition-all duration-300 shadow-sm hover:shadow-md ${
                    Object.keys(filters).length > 0 
                    ? 'bg-gradient-to-r from-blue-50 to-blue-100/50 dark:from-blue-900/40 dark:to-blue-900/20 border-blue-300/50 dark:border-blue-800/50 text-blue-700 dark:text-blue-300 hover:from-blue-100 hover:to-blue-150/50 dark:hover:from-blue-900/50 dark:hover:to-blue-900/30 shadow-blue-500/10' 
                    : 'bg-slate-50/80 dark:bg-[#252525]/80 hover:bg-slate-100/80 dark:hover:bg-[#333]/80 border-slate-200/60 dark:border-[#333]/60 text-slate-600 dark:text-stone-300 hover:border-slate-300 dark:hover:border-zinc-600'
                }`}
            >
                <Filter size={16} strokeWidth={2.5} />
                <span className="uppercase tracking-wide text-[11px] font-bold">
                    {Object.keys(filters).length > 0 ? `${Object.keys(filters).length} Filtro${Object.keys(filters).length > 1 ? 's' : ''}` : 'Filtros Avançados'}
                </span>
            </button>
        </div>
      </div>

        <div className="overflow-x-auto overflow-y-auto flex-1 relative custom-scrollbar w-full min-w-0">
        <table className="border-collapse table-fixed w-full min-w-full">
          <thead className="sticky top-0 z-20 bg-gradient-to-b from-slate-50/95 to-slate-100/95 dark:from-[#1b1b1b]/95 dark:to-zinc-900/95 backdrop-blur-sm shadow-lg shadow-black/5 dark:shadow-black/20 border-b-2 border-slate-200/60 dark:border-[#333]/60">
            <tr className="border-b border-slate-200/60 dark:border-[#333]/60">
                <th className="sticky left-0 z-30 bg-gradient-to-b from-slate-50/95 to-slate-100/95 dark:from-[#1b1b1b]/95 dark:to-zinc-900/95 backdrop-blur-sm w-[40px] min-w-[40px] h-[48px] border-r border-slate-200/60 dark:border-[#333]/60">
                     <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}
                            disabled={!onSelectionChange}
                            className="appearance-none w-4 h-4 border-2 border-slate-300 dark:border-slate-600 rounded-md bg-white dark:bg-[#2a2a2a] checked:bg-gradient-to-br checked:from-emerald-500 checked:to-emerald-600 checked:border-emerald-500 transition-all cursor-pointer relative shadow-sm hover:shadow-md hover:border-emerald-400 dark:hover:border-emerald-500"
                         />
                     </div>
                </th>
                <th className="sticky left-[40px] z-30 bg-gradient-to-b from-slate-50/95 to-slate-100/95 dark:from-[#1b1b1b]/95 dark:to-zinc-900/95 backdrop-blur-sm w-[60px] min-w-[60px] h-[48px] border-r border-slate-200/60 dark:border-[#333]/60 px-2 text-left">
                     <div className="flex items-center h-full w-full uppercase font-bold text-slate-600 dark:text-[#e0e0e0] tracking-wider text-[11px]">
                        Ações
                     </div>
                </th>

               {columns.map((col, idx) => (
                   <th 
                        key={idx} 
                        onClick={() => handleSort(col.field)}
                        className="h-[48px] border-r border-slate-200/60 dark:border-[#333]/60 bg-gradient-to-b from-slate-50/95 to-slate-100/95 dark:from-[#1b1b1b]/95 dark:to-zinc-900/95 backdrop-blur-sm px-4 relative group hover:from-slate-100 hover:to-slate-150 dark:hover:from-[#222] dark:hover:to-zinc-800 transition-all duration-200 cursor-pointer select-none" 
                        style={{ width: col.width, minWidth: col.width }}
                    >
                       <div className="flex items-center justify-between h-full w-full">
                           <div className="flex items-center gap-2">
                                <span className={`uppercase font-bold tracking-wider text-[11px] transition-colors ${sortConfig.key === col.field ? 'text-emerald-600 dark:text-emerald-400 drop-shadow-sm' : 'text-slate-600 dark:text-[#e0e0e0]'}`}>
                                    {col.header}
                                </span>
                                {sortConfig.key === col.field && (
                                    <div className="w-1.5 h-1.5 rounded-full bg-emerald-500 animate-pulse shadow-lg shadow-emerald-500/50" />
                                )}
                           </div>
                       </div>
                   </th>
               ))}
                <th className="bg-gradient-to-b from-slate-50/95 to-slate-100/95 dark:from-[#1b1b1b]/95 dark:to-zinc-900/95 backdrop-blur-sm border-b border-slate-200/60 dark:border-[#333]/60"></th>
            </tr>
          </thead>

          <tbody className="bg-white/50 dark:bg-[#151515]/50">
            {paginatedData.map((row, idx) => (
                <tr 
                  key={idx} 
                  onClick={() => onRowClick && onRowClick(row)}
                  className={`h-[52px] border-b border-slate-100/60 dark:border-[#252525]/60 hover:bg-gradient-to-r hover:from-emerald-50/30 hover:to-transparent dark:hover:from-emerald-900/10 dark:hover:to-transparent transition-all duration-200 group text-sm ${idx % 2 === 0 ? 'bg-white/80 dark:bg-[#151515]/80' : 'bg-slate-50/30 dark:bg-[#181818]/30'} ${onRowClick ? 'cursor-pointer hover:shadow-sm' : ''}`}
                >
                    <td className={`sticky left-0 z-10 border-r border-slate-100/60 dark:border-[#252525]/60 px-0 text-center transition-colors ${idx % 2 === 0 ? 'bg-white/80 dark:bg-[#151515]/80' : 'bg-slate-50/30 dark:bg-[#181818]/30'} group-hover:bg-emerald-50/30 dark:group-hover:bg-emerald-900/10`}>
                      <div className="flex items-center justify-center h-full w-full">
                          <input 
                            type="checkbox" 
                            checked={selectedIds.includes(row[rowKey])}
                            onChange={() => handleSelectRow(row[rowKey])}
                            disabled={!onSelectionChange}
                            className="appearance-none w-4 h-4 border-2 border-slate-300 dark:border-slate-600 rounded-md bg-white dark:bg-[#2a2a2a] checked:bg-gradient-to-br checked:from-emerald-500 checked:to-emerald-600 checked:border-emerald-500 transition-all cursor-pointer relative shadow-sm hover:shadow-md hover:border-emerald-400 dark:hover:border-emerald-500"
                          />
                      </div>
                    </td>

                    <td className={`sticky left-[40px] z-10 border-r border-slate-100/60 dark:border-[#252525]/60 px-0 text-center transition-colors ${idx % 2 === 0 ? 'bg-white/80 dark:bg-[#151515]/80' : 'bg-slate-50/30 dark:bg-[#181818]/30'} group-hover:bg-emerald-50/30 dark:group-hover:bg-emerald-900/10`}>
                        <div className="flex items-center justify-center h-full w-full gap-2">
                             <button 
                               onClick={(e) => { e.stopPropagation(); onEdit && onEdit(row); }} 
                               className="text-slate-500 dark:text-stone-500 hover:text-emerald-600 dark:hover:text-emerald-400 transition-all duration-200 p-1.5 rounded-lg hover:bg-emerald-50 dark:hover:bg-emerald-900/20 hover:scale-110 active:scale-95"
                             >
                                <Edit2 size={18} strokeWidth={2.5} />
                             </button>
                             {onDelete && (
                               <button 
                                 onClick={(e) => { e.stopPropagation(); onDelete(row); }} 
                                 className="text-slate-500 dark:text-stone-500 hover:text-rose-600 dark:hover:text-rose-400 transition-all duration-200 p-1.5 rounded-lg hover:bg-rose-50 dark:hover:bg-rose-900/20 hover:scale-110 active:scale-95"
                               >
                                  <Trash2 size={18} strokeWidth={2.5} />
                               </button>
                             )}
                        </div>
                    </td>
                    
                    {columns.map((col, cIdx) => (
                        <td key={cIdx} className="border-r border-slate-100/60 dark:border-[#252525]/60 px-4 whitespace-nowrap overflow-hidden text-ellipsis text-slate-700 dark:text-stone-300 transition-colors group-hover:text-slate-900 dark:group-hover:text-stone-100">
                             {col.render ? col.render(row) : (
                                 <span className={col.className}>{row[col.field] || '-'}</span>
                             )}
                        </td>
                    ))}
                     <td className=""></td>
                </tr>
            ))}
             {!loading && paginatedData.length === 0 && (
                 <tr>
                     <td colSpan={columns.length + 3} className="h-24 text-center text-stone-500 italic">
                         Nenhum registro disponível.
                     </td>
                 </tr>
             )}
          </tbody>
        </table>
      </div>

      {/* Enhanced Footer */}
      <div className="bg-gradient-to-r from-slate-50/90 via-white/50 to-slate-50/90 dark:from-[#1b1b1b]/90 dark:via-zinc-900/50 dark:to-[#1b1b1b]/90 backdrop-blur-sm border-t border-slate-200/60 dark:border-[#333]/60 h-[52px] flex items-center justify-between px-4 overflow-hidden select-none shadow-inner">
            <div className="flex h-full items-center gap-4">
                 <div className="flex items-center gap-2 px-5 h-full relative group min-w-[140px]">
                    <div className="absolute left-0 top-2 bottom-2 w-[4px] bg-gradient-to-b from-emerald-500 to-emerald-600 rounded-r-md shadow-lg shadow-emerald-500/30"></div>
                    <span className="text-[10px] uppercase font-bold text-slate-500 dark:text-slate-400 tracking-wider">Total:</span>
                    <span className="text-base font-bold text-slate-800 dark:text-stone-200 drop-shadow-sm">{processedData.length}</span>
                    <div className="absolute right-0 top-2 bottom-2 w-[1px] bg-slate-200/60 dark:bg-[#333]/60"></div>
                 </div>
                 <div className="flex items-center gap-2 px-5 h-full relative group min-w-[120px]">
                    <span className="text-[10px] uppercase font-bold text-slate-500 dark:text-slate-400 tracking-wider">Página:</span>
                    <span className="text-base font-bold text-slate-800 dark:text-stone-200 drop-shadow-sm">{currentPage} / {totalPages || 1}</span>
                 </div>
            </div>

            <div className="flex items-center gap-1.5 pr-2">
                <button 
                  onClick={() => setCurrentPage(1)} 
                  disabled={currentPage === 1} 
                  className="w-8 h-8 flex items-center justify-center rounded-lg bg-white/80 dark:bg-[#151515]/80 border border-slate-200/60 dark:border-[#333]/60 hover:border-emerald-500 hover:bg-emerald-50/50 dark:hover:bg-emerald-900/20 text-slate-500 dark:text-stone-400 disabled:opacity-30 disabled:cursor-not-allowed transition-all duration-200 hover:scale-110 active:scale-95 shadow-sm hover:shadow-md"
                >
                     <ChevronsLeft size={16} strokeWidth={2.5} />
                </button>
                <button 
                  onClick={() => setCurrentPage(p => Math.max(1, p - 1))} 
                  disabled={currentPage === 1} 
                  className="w-8 h-8 flex items-center justify-center rounded-lg bg-white/80 dark:bg-[#151515]/80 border border-slate-200/60 dark:border-[#333]/60 hover:border-emerald-500 hover:bg-emerald-50/50 dark:hover:bg-emerald-900/20 text-slate-500 dark:text-stone-400 disabled:opacity-30 disabled:cursor-not-allowed transition-all duration-200 hover:scale-110 active:scale-95 shadow-sm hover:shadow-md"
                >
                     <ChevronLeft size={16} strokeWidth={2.5} />
                </button>
                <div className="flex gap-1 mx-1">
                    <button className="w-8 h-8 flex items-center justify-center rounded-lg bg-gradient-to-br from-emerald-500 to-emerald-600 text-white font-bold text-[12px] shadow-lg shadow-emerald-500/30 hover:shadow-xl hover:shadow-emerald-500/40 transition-all duration-200 hover:scale-110 active:scale-95">
                        {currentPage}
                    </button>
                </div>
                 <button 
                  onClick={() => setCurrentPage(p => Math.min(totalPages, p + 1))} 
                  disabled={currentPage === totalPages || totalPages === 0} 
                  className="w-8 h-8 flex items-center justify-center rounded-lg bg-white/80 dark:bg-[#151515]/80 border border-slate-200/60 dark:border-[#333]/60 hover:border-emerald-500 hover:bg-emerald-50/50 dark:hover:bg-emerald-900/20 text-slate-500 dark:text-stone-400 disabled:opacity-30 disabled:cursor-not-allowed transition-all duration-200 hover:scale-110 active:scale-95 shadow-sm hover:shadow-md"
                >
                     <ChevronRight size={16} strokeWidth={2.5} />
                </button>
                 <button 
                  onClick={() => setCurrentPage(totalPages)} 
                  disabled={currentPage === totalPages || totalPages === 0} 
                  className="w-8 h-8 flex items-center justify-center rounded-lg bg-white/80 dark:bg-[#151515]/80 border border-slate-200/60 dark:border-[#333]/60 hover:border-emerald-500 hover:bg-emerald-50/50 dark:hover:bg-emerald-900/20 text-slate-500 dark:text-stone-400 disabled:opacity-30 disabled:cursor-not-allowed transition-all duration-200 hover:scale-110 active:scale-95 shadow-sm hover:shadow-md"
                >
                    <ChevronsRight size={16} strokeWidth={2.5} />
                </button>
            </div>
      </div>
      </div>

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

export default ExcelTable;
