import React, { useState, useRef } from 'react';
import { Table, Search, Filter, Download, FileSpreadsheet, Plus, Layers, Database, History, MoreVertical, CheckCircle2, AlertCircle, FileText, RefreshCw, Archive, X, Upload } from 'lucide-react';
import { useSpreadsheets } from '../hooks/useSpreadsheets';

const Modal = ({ isOpen, onClose, title, children }) => {
  if (!isOpen) return null;
  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/60 backdrop-blur-sm animate-in fade-in duration-300">
      <div className="bg-white dark:bg-[#1b1b1b] w-full max-w-2xl rounded-[32px] border border-slate-200 dark:border-white/5 shadow-2xl overflow-hidden animate-in zoom-in-95 duration-300">
        <div className="flex items-center justify-between p-6 border-b border-slate-100 dark:border-white/5">
          <h3 className="text-xl font-bold text-slate-800 dark:text-white">{title}</h3>
          <button onClick={onClose} className="p-2 hover:bg-slate-100 dark:hover:bg-white/5 rounded-full transition-colors text-slate-400">
            <X size={20} />
          </button>
        </div>
        <div className="p-8 max-h-[80vh] overflow-y-auto">
          {children}
        </div>
      </div>
    </div>
  );
};

const GrPlanilhasView = () => {
  const [activeTab, setActiveTab] = useState('ALL');
  const [searchTerm, setSearchTerm] = useState('');
  const [isImportModalOpen, setIsImportModalOpen] = useState(false);
  const [importStep, setImportStep] = useState(1); // 1: Select, 2: Preview, 3: Success
  const fileInputRef = useRef(null);
  
  const { data, stats, loading, importing, error, refresh, archiveRow, importSpreadsheet } = useSpreadsheets({
    archived: activeTab === 'ARQUIVADOS'
  });

  const filteredData = data.filter(row => {
    const matchesSearch = row.data.motorista?.toLowerCase().includes(searchTerm.toLowerCase()) ||
                         row.data.cpf?.includes(searchTerm);
    return matchesSearch;
  });

  const handleFileSelect = () => {
    setImportStep(2);
    // Simulação de leitura de arquivo
    setTimeout(() => {
      // preview já estaria pronto no real
    }, 1000);
  };

  const handleConfirmImport = async () => {
    try {
      await importSpreadsheet({
        clientId: 'IMPERIO',
        rows: [
          { motorista: 'NOVO MOTORISTA', cpf: '000.000.000-00', validade_cnh: '2026-12-31' }
        ]
      });
      setImportStep(3);
    } catch (err) {
      alert(err.message);
    }
  };

  const handleArchive = async (id) => {
    if (!confirm('Tem certeza que deseja arquivar este registro?')) return;
    try {
      await archiveRow(id);
      alert('Registro arquivado com sucesso.');
    } catch (err) {
      alert(`Erro ao arquivar: ${err.message}`);
    }
  };

  const categories = [
    { id: 'ALL', icon: Table, count: stats?.total || 0, color: 'text-[var(--gr-primary)]', label: 'Todos' },
    { id: 'IMPERIO', icon: FileSpreadsheet, count: stats?.byClient?.IMPERIO || 0, color: 'text-emerald-500', label: 'Império' },
    { id: 'ORTOBOM_RJ', icon: Database, count: stats?.byClient?.ORTOBOM_RJ || 0, color: 'text-orange-500', label: 'Ortobom RJ' },
    { id: 'ARQUIVADOS', icon: History, count: stats?.archived || 0, color: 'text-slate-400', label: 'Arquivados' }
  ];

  return (
    <div className="flex flex-col gap-8 p-6 md:p-10 animate-in fade-in slide-in-from-bottom-4 duration-700">
      <header className="flex flex-col md:flex-row md:items-end justify-between gap-6">
        <div className="space-y-2">
          <h1 className="text-4xl md:text-6xl font-bold text-slate-800 dark:text-white tracking-tighter leading-none">
            Hub de <span className="text-[var(--gr-primary)]">Planilhas</span>
          </h1>
          <p className="text-slate-400 dark:text-slate-500 text-base md:text-lg font-medium italic opacity-80">
            Processamento de dados brutos e relatórios analíticos em massa
          </p>
        </div>

        <div className="flex gap-3">
          <button onClick={refresh} className="p-3 bg-slate-100 dark:bg-[#141414] rounded-full text-slate-500 hover:bg-slate-200 transition-all">
            <RefreshCw size={20} className={loading ? 'animate-spin' : ''} />
          </button>
          <button 
            onClick={() => { setImportStep(1); setIsImportModalOpen(true); }}
            className="flex items-center gap-2 px-8 py-4 bg-[var(--gr-primary)] text-white rounded-[24px] font-bold text-xs uppercase tracking-widest hover:bg-[var(--gr-primary)]/90 transition-all shadow-xl shadow-[var(--gr-primary)]/20"
          >
            <Plus size={18} />
            Importar Excel
          </button>
        </div>
      </header>

      {/* Categories Cards */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        {categories.map((cat) => (
          <button 
            key={cat.id} 
            onClick={() => setActiveTab(cat.id)}
            className={`p-6 rounded-[32px] border text-left transition-all ${activeTab === cat.id ? 'bg-white dark:bg-[#1b1b1b] border-[var(--gr-primary)]/30 shadow-xl' : 'bg-transparent border-slate-200 dark:border-white/5'}`}
          >
            <cat.icon size={24} className={`mb-4 ${cat.color}`} />
            <h4 className="text-[10px] font-bold uppercase text-slate-400 tracking-widest">{cat.label}</h4>
            <div className="text-2xl font-bold text-slate-800 dark:text-white">{cat.count}</div>
          </button>
        ))}
      </div>

      {/* Main List Table */}
      <div className="bg-white dark:bg-[#1b1b1b] rounded-[40px] border border-slate-200 dark:border-white/5 overflow-hidden">
        <div className="p-8 border-b border-slate-100 dark:border-white/5 flex items-center justify-between">
          <div className="relative group">
            <Search className="absolute left-4 top-1/2 -translate-y-1/2 text-slate-400" size={16} />
            <input 
              type="text" 
              placeholder="PESQUISAR MOTORISTA OU CPF..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="pl-12 pr-4 py-3 bg-slate-50 dark:bg-[#141414] border-none rounded-2xl text-[10px] font-bold w-80 outline-none uppercase"
            />
          </div>
          <button onClick={() => alert('Exportando lista atual...')} className="p-3 bg-slate-50 dark:bg-[#141414] rounded-2xl text-slate-500 hover:text-[var(--gr-primary)]">
            <Download size={20} />
          </button>
        </div>

        <div className="overflow-x-auto text-nowrap">
          <table className="w-full text-left border-collapse">
            <thead>
              <tr className="bg-slate-50/50 dark:bg-white/[0.02] border-b border-slate-100 dark:border-white/5">
                <th className="p-6 text-[10px] font-bold text-slate-400 uppercase tracking-widest">Motorista</th>
                <th className="p-6 text-[10px] font-bold text-slate-400 uppercase tracking-widest">CPF</th>
                <th className="p-6 text-[10px] font-bold text-slate-400 uppercase tracking-widest">Validade CNH</th>
                <th className="p-6 text-[10px] font-bold text-slate-400 uppercase tracking-widest">Cliente</th>
                <th className="p-6"></th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-100 dark:divide-white/5">
              {filteredData.map((row) => (
                <tr key={row.id} className="hover:bg-slate-50 dark:hover:bg-white/[0.02] group">
                  <td className="p-6">
                    <div className="flex items-center gap-3">
                      <div className="p-2 bg-emerald-50 dark:bg-emerald-900/10 rounded-lg text-emerald-500">
                        <FileText size={16} />
                      </div>
                      <span className="font-bold text-sm text-slate-800 dark:text-slate-200">{row.data.motorista}</span>
                    </div>
                  </td>
                  <td className="p-6 text-xs font-bold text-slate-500">{row.data.cpf}</td>
                  <td className="p-6">
                    <span className="px-3 py-1 bg-slate-100 dark:bg-[#141414] rounded-full text-[10px] font-bold text-slate-600 dark:text-slate-400">
                      {row.data.validade_cnh}
                    </span>
                  </td>
                  <td className="p-6 text-[10px] font-bold text-slate-400 uppercase">{row.clientId}</td>
                  <td className="p-6 text-right">
                    {!row.archived && (
                      <button onClick={() => handleArchive(row.id)} className="p-2 text-slate-400 hover:text-orange-500 opacity-0 group-hover:opacity-100 transition-all">
                        <Archive size={18} />
                      </button>
                    )}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {/* Modal de Importação */}
      <Modal isOpen={isImportModalOpen} onClose={() => setIsImportModalOpen(false)} title="Importar Base de Dados (Excel)">
        {importStep === 1 && (
          <div className="space-y-6">
            <div 
              onClick={() => fileInputRef.current?.click()}
              className="border-2 border-dashed border-slate-200 dark:border-white/5 rounded-[32px] p-16 flex flex-col items-center justify-center gap-6 hover:border-[var(--gr-primary)]/40 hover:bg-slate-50/50 transition-all cursor-pointer group"
            >
              <div className="p-6 bg-emerald-500/10 rounded-full text-emerald-500 group-hover:scale-110 transition-transform">
                <Upload size={40} />
              </div>
              <div className="text-center">
                <p className="text-lg font-bold text-slate-800 dark:text-white">Selecione o arquivo Excel</p>
                <p className="text-sm text-slate-400 font-medium">Formato .xlsx ou .csv esperado</p>
              </div>
            </div>
            <input type="file" ref={fileInputRef} onChange={handleFileSelect} className="hidden" accept=".xlsx,.xls,.csv" />
          </div>
        )}

        {importStep === 2 && (
          <div className="space-y-6">
            <div className="p-6 bg-slate-50 dark:bg-[#141414] rounded-3xl space-y-4 border border-slate-200 dark:border-white/5">
              <h4 className="text-sm font-bold text-slate-800 dark:text-white uppercase flex items-center gap-2">
                <CheckCircle2 size={18} className="text-emerald-500" />
                Deteção de 6 registros prontos
              </h4>
              <div className="space-y-2">
                <div className="p-3 bg-white dark:bg-[#1b1b1b] rounded-xl text-xs flex justify-between">
                  <span className="text-slate-500">Mapeamento:</span>
                  <span className="font-bold text-[var(--gr-primary)]">COLUNA A → MOTORISTA</span>
                </div>
                <div className="p-3 bg-white dark:bg-[#1b1b1b] rounded-xl text-xs flex justify-between">
                  <span className="text-slate-500">Validado:</span>
                  <span className="font-bold text-emerald-500">100% CORRETO</span>
                </div>
              </div>
            </div>
            <div className="flex gap-4">
              <button onClick={() => setImportStep(1)} className="flex-1 py-4 bg-slate-100 dark:bg-[#141414] text-slate-800 rounded-2xl font-bold uppercase text-xs">Voltar</button>
              <button 
                onClick={handleConfirmImport} 
                disabled={importing}
                className="flex-2 py-4 bg-emerald-500 text-white rounded-2xl font-bold uppercase text-xs hover:bg-emerald-600 transition-all"
              >
                {importing ? <RefreshCw className="animate-spin" /> : 'Confirmar Importação'}
              </button>
            </div>
          </div>
        )}

        {importStep === 3 && (
          <div className="py-12 flex flex-col items-center justify-center gap-6 animate-in zoom-in duration-500">
            <div className="w-24 h-24 bg-emerald-500/10 rounded-full flex items-center justify-center">
              <CheckCircle2 size={48} className="text-emerald-500" />
            </div>
            <div className="text-center">
              <h3 className="text-2xl font-bold text-slate-800 dark:text-white">Importado com Sucesso!</h3>
              <p className="text-slate-500 italic">Seus dados já estão disponíveis na listagem.</p>
            </div>
            <button 
              onClick={() => setIsImportModalOpen(false)}
              className="px-12 py-4 bg-slate-800 text-white rounded-2xl font-bold uppercase text-xs mt-4"
            >
              Fechar
            </button>
          </div>
        )}
      </Modal>
    </div>
  );
};

export default GrPlanilhasView;
