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

// Simplified version of ExcelTable for CNAB
// Adapted for inline validation and editing needs
const CnabExcelTable = ({ 
    data, 
    columns, 
    onRowClick, // Handler para clique na linha (substitui onEdit)
    onDelete, // New prop for row deletion
    loading = false, 
    pageSize: initialPageSize = 10,
    selectedIds = [],
    onSelectionChange,
    rowKey = 'id'
}) => {
  // Debug: verificar colunas recebidas
  React.useEffect(() => {
    if (columns && columns.length > 0) {
      console.log('🔍 [CnabExcelTable] Colunas recebidas:', columns.length, 'Colunas:', columns.map(c => c.header || c.field));
    }
  }, [columns]);
  const [sortConfig, setSortConfig] = useState({ key: null, direction: 'asc' });
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(initialPageSize);

  // Sorting Logic
  const processedData = React.useMemo(() => {
    if (!data) return [];
    let result = [...data];

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

  // Pagination Logic
  const totalPages = Math.ceil(processedData.length / pageSize);
  const paginatedData = React.useMemo(() => {
    const startIndex = (currentPage - 1) * pageSize;
    return processedData.slice(startIndex, startIndex + pageSize);
  }, [processedData, currentPage, pageSize]);

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

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

  const handleSelectAll = (e) => {
    if (!onSelectionChange) return;
    if (e.target.checked) {
        onSelectionChange(processedData.map(item => item[rowKey]));
    } 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.length > 0 && processedData.every(item => selectedIds.includes(item[rowKey]));
  const isIndeterminate = processedData.some(item => selectedIds.includes(item[rowKey])) && !isAllSelected;

  return (
    <div className="bg-white dark:bg-[#1b1b1b] border border-slate-200 dark:border-zinc-800 rounded-2xl flex flex-col h-full w-full overflow-hidden shadow-xl text-[clamp(0.75vw,0.7rem,0.9rem)] font-sans">
        
        {/* Header Actions */}
        <div className="px-4 py-3 bg-white dark:bg-[#1b1b1b] border-b border-slate-200 dark:border-zinc-800 flex justify-between items-center">
             <div className="flex items-center gap-2">
                 <span className="text-slate-700 dark:text-zinc-300 font-bold uppercase tracking-widest text-[clamp(0.75rem,0.9vw,0.8125rem)]">Total de Registros:</span>
                 <span className="text-emerald-500 font-mono font-bold">{processedData.length}</span>
             </div>
             {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 Selecionados ({selectedIds.length})</span>
                 </button>
             )}
        </div>

        {/* Table Area */}
        <div className="overflow-auto flex-1 custom-scrollbar">
            <table className="w-full border-collapse" style={{ minWidth: '100%', tableLayout: 'auto' }}>
                <thead className="sticky top-0 z-20 bg-white dark:bg-[#1b1b1b] shadow-lg shadow-black/10 dark:shadow-black/20">
                    <tr>
                        {onSelectionChange && (
                            <th className="w-[40px] border-r border-slate-200 dark:border-zinc-800 bg-white dark:bg-[#1b1b1b] p-0">
                                <div className="flex items-center justify-center h-full">
                                    <input 
                                        type="checkbox" 
                                        checked={isAllSelected}
                                        ref={el => el && (el.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 cursor-pointer 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>
                        )}

                        {columns.map((col, idx) => {
                            // Não permitir ordenação em colunas de ações
                            const isActionColumn = col.field === 'acoes' || col.header === 'Ações';
                            // Primeira coluna fixa (ações) - sticky apenas durante scroll
                            const isFirstFixed = idx === 0 && (col.isFixed || isActionColumn);
                            // Calcula o left baseado na coluna de seleção se existir
                            const stickyLeft = onSelectionChange ? '40px' : '0';
                            return (
                            <th 
                                key={idx}
                                style={{ 
                                    width: col.width, 
                                    minWidth: col.width,
                                    ...(isFirstFixed && {
                                        position: 'sticky',
                                        left: stickyLeft,
                                        zIndex: 30
                                    })
                                }}
                                onClick={() => !isActionColumn && handleSort(col.field)}
                                className={cn(
                                    "h-[40px] px-3 border-r border-slate-200 dark:border-zinc-800 text-left transition-colors",
                                    !isActionColumn && "cursor-pointer group hover:bg-slate-100 dark:hover:bg-zinc-800/50",
                                    isFirstFixed && "bg-white dark:bg-[#1b1b1b]"
                                )}
                            >
                                <div className="flex items-center justify-between">
                                    <span className={cn(
                                        "font-bold uppercase tracking-wider text-[clamp(0.75rem,0.9vw,0.8125rem)]",
                                        sortConfig.key === col.field ? "text-emerald-500" : "text-slate-700 dark:text-zinc-300 group-hover:text-slate-900 dark:group-hover:text-zinc-200"
                                    )}>
                                        {col.header}
                                    </span>
                                    {sortConfig.key === col.field && (
                                        <div className="text-emerald-500 text-[clamp(0.75rem,0.9vw,0.8125rem)]">
                                            {sortConfig.direction === 'asc' ? '▲' : '▼'}
                                        </div>
                                    )}
                                </div>
                            </th>
                            );
                        })}
                    </tr>
                </thead>
                <tbody className="bg-white dark:bg-[#151515]">
                    {paginatedData.map((row, rIdx) => (
                        <tr 
                            key={row[rowKey] || rIdx} 
                            onClick={() => onRowClick && onRowClick(row)}
                            className={cn(
                                "border-b border-slate-200 dark:border-zinc-800/50 hover:bg-slate-50 dark:hover:bg-zinc-800/30 transition-colors group",
                                onRowClick && "cursor-pointer"
                            )}
                        >
                            {onSelectionChange && (
                                <td 
                                    className={cn(
                                        "border-r border-slate-200 dark:border-zinc-800",
                                        rIdx % 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()} // Previne que o clique no checkbox dispare o onRowClick
                                >
                                    <div className="flex items-center justify-center py-2">
                                        <input 
                                            type="checkbox"
                                            checked={selectedIds.includes(row[rowKey])}
                                            onChange={() => handleSelectRow(row[rowKey])}
                                            onClick={(e) => e.stopPropagation()} // Previne propagação
                                            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 cursor-pointer 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>
                            )}
                            {columns.map((col, cIdx) => {
                                const isActionColumn = col.field === 'acoes' || col.header === 'Ações';
                                // Primeira coluna fixa (ações) - sticky apenas durante scroll
                                const isFirstFixed = cIdx === 0 && (col.isFixed || isActionColumn);
                                // Determina o background baseado na linha (par/ímpar) e hover
                                const rowBg = rIdx % 2 === 0 ? 'bg-white dark:bg-[#151515]' : 'bg-slate-50 dark:bg-[#181818]';
                                // Calcula o left baseado na coluna de seleção se existir
                                const stickyLeft = onSelectionChange ? '40px' : '0';
                                return (
                                <td 
                                    key={cIdx} 
                                    className={cn(
                                        "border-r border-slate-200 dark:border-zinc-800 px-3 py-2",
                                        isActionColumn ? '' : 'text-slate-700 dark:text-zinc-300',
                                        isFirstFixed && cn(
                                            "sticky",
                                            rowBg,
                                            "group-hover:bg-slate-100 dark:group-hover:bg-zinc-800/30"
                                        )
                                    )}
                                    style={{ 
                                        width: col.width, 
                                        minWidth: col.width,
                                        ...(isFirstFixed && {
                                            position: 'sticky',
                                            left: stickyLeft,
                                            zIndex: 10
                                        })
                                    }}
                                >
                                    {col.render ? col.render(row) : (
                                        <div className={isActionColumn ? '' : 'whitespace-nowrap overflow-hidden text-ellipsis'}>
                                            {row[col.field] || '---'}
                                        </div>
                                    )}
                                </td>
                                );
                            })}
                        </tr>
                    ))}
                    {paginatedData.length === 0 && (
                        <tr>
                            <td colSpan={columns.length + (onSelectionChange ? 1 : 0)} className="py-8 text-center text-slate-500 dark:text-zinc-300 italic">
                                Nenhum registro encontrado.
                            </td>
                        </tr>
                    )}
                </tbody>
            </table>
        </div>

        {/* Footer Pagination */}
        <div className="h-[40px] border-t border-slate-200 dark:border-zinc-800 bg-white dark:bg-[#1b1b1b] flex items-center justify-between px-4">
             <div className="text-[clamp(0.75rem,0.9vw,0.8125rem)] text-slate-700 dark:text-zinc-300 uppercase font-bold tracking-wider">
                 Página {currentPage} de {totalPages || 1}
             </div>
             <div className="flex gap-1">
                 <button 
                    onClick={() => setCurrentPage(1)} disabled={currentPage === 1}
                    className="p-1 hover:bg-slate-100 dark:hover:bg-zinc-800 rounded text-slate-600 dark:text-zinc-400 disabled:opacity-30"
                 >
                     <ChevronsLeft size={16} />
                 </button>
                 <button 
                    onClick={() => setCurrentPage(c => Math.max(1, c-1))} disabled={currentPage === 1}
                    className="p-1 hover:bg-slate-100 dark:hover:bg-zinc-800 rounded text-slate-600 dark:text-zinc-400 disabled:opacity-30"
                 >
                     <ChevronLeft size={16} />
                 </button>
                 <button 
                    onClick={() => setCurrentPage(c => Math.min(totalPages, c+1))} disabled={currentPage === totalPages}
                    className="p-1 hover:bg-slate-100 dark:hover:bg-zinc-800 rounded text-slate-600 dark:text-zinc-400 disabled:opacity-30"
                 >
                     <ChevronRight size={16} />
                 </button>
                  <button 
                    onClick={() => setCurrentPage(totalPages)} disabled={currentPage === totalPages}
                    className="p-1 hover:bg-slate-100 dark:hover:bg-zinc-800 rounded text-slate-600 dark:text-zinc-400 disabled:opacity-30"
                 >
                     <ChevronsRight size={16} />
                 </button>
             </div>
        </div>
    </div>
  );
};

export default CnabExcelTable;
