import React, { useState, useMemo, useEffect, useCallback } from 'react';
import { Search, Plus, X } from 'lucide-react';
import { toast } from 'sonner';
import { handleGrError } from '../utils/grErrorHandler';
import ExcelTable from '../components/ExcelTable';


import { GrRegistrationDetails } from '../components/GrRegistrationDetails';
import { useGrStore } from '../services/useGrStore';
import * as grService from '../services/grService';

import { useNavigate } from 'react-router-dom';

const GrRegistrationsSimplified = () => {
  const navigate = useNavigate();
  const { userData } = useGrStore();
  const [filterType, setFilterType] = useState('Interno');
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedCard, setSelectedCard] = useState(null);
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(false);

  const userGroup = userData?.usuario?.grupo || 'Administrador';
  const userBase = userData?.usuario?.base || '';

  const fetchData = useCallback(async () => {
    if (!userData || !userData.usuario) {
      console.warn("GR: No user data available yet to fetch registrations.");
      return;
    }
    
    setLoading(true);
    try {
      const params = {
        grupo: userGroup,
        base: userBase,
        filtro: `Cadastro ${filterType}`
      };
      
      const response = await grService.getDriversByFilter(params);
      const driverData = response.Base_Dados_API || response.dados || response;
      setData(Array.isArray(driverData) ? driverData : (driverData.dados || []));
    } catch (error) {
      handleGrError(error, "Erro ao carregar cadastros");
    } finally {
      setLoading(false);
    }
  }, [userData, userGroup, userBase, filterType]);

  useEffect(() => {
    fetchData();
  }, [fetchData]);

  const filteredData = useMemo(() => {
    if (!data) return [];
    return data.filter(item => {
      const matchesSearch = 
        (item.nome_completo || '').toLowerCase().includes(searchTerm.toLowerCase()) ||
        (item.cpf || '').includes(searchTerm) ||
        (item.placa_veiculo || '').toLowerCase().includes(searchTerm.toLowerCase());
      
      return matchesSearch;
    });
  }, [data, searchTerm]);

  const handleNewRegistration = () => {
    setSelectedCard({
      id: null,
      title: 'Novo Cadastro',
      isNew: true
    });
  };

  const handleEditRegistration = (registration) => {
    setSelectedCard({
      ...registration,
      id: registration.iddrivers,
      title: registration.nome_completo
    });
  };

  const tableColumns = [
    { header: 'ID', field: 'iddrivers', width: '80px' },
    { header: 'NOME', field: 'nome_completo', width: '200px', className: 'font-bold text-[var(--gr-primary)]' },
    { header: 'CPF', field: 'cpf', width: '140px', className: 'font-mono' },
    { header: 'PLACA', field: 'placa_veiculo', width: '100px', className: 'font-mono' },
    { header: 'MODALIDADE', field: 'modalidade', width: '140px' },
    { header: 'BASE', field: 'base', width: '120px' },
    { header: 'STATUS', field: 'global_status', width: '180px' },
    { header: 'DATA CADASTRO', field: 'data_cadastro', width: '140px' },
  ];

  return (
    <div className="flex flex-col gap-6">
      {/* Controls */}
      <div className="flex flex-wrap items-center justify-between gap-4">
        {/* Filter Buttons */}
        <div className="flex items-center bg-slate-100 dark:bg-slate-800/50 p-1.5 rounded-[24px] border border-slate-200 dark:border-white/5 shadow-inner">
          <span className="pl-4 pr-2 text-[9px] font-bold text-slate-400 uppercase tracking-widest hidden lg:block self-center mt-0.5">Filtro:</span>
          <button 
            onClick={() => setFilterType('Externo')}
            className={`px-6 py-2.5 rounded-[20px] text-[10px] font-bold uppercase tracking-wider transition-all duration-300 ${filterType === 'Externo' ? 'bg-white dark:bg-slate-700 shadow-lg text-slate-800 dark:text-white transform scale-[1.05]' : 'text-slate-500 hover:text-slate-700 dark:hover:text-slate-300'}`}
          >
            Externo
          </button>
          <button 
            onClick={() => setFilterType('Interno')}
            className={`px-6 py-2.5 rounded-[20px] text-[10px] font-bold uppercase tracking-wider transition-all duration-300 ${filterType === 'Interno' ? 'bg-white dark:bg-slate-700 shadow-lg text-slate-800 dark:text-white transform scale-[1.05]' : 'text-slate-500 hover:text-slate-700 dark:hover:text-slate-300'}`}
          >
            Interno
          </button>
        </div>

        {/* Search and New Button */}
        <div className="flex items-center gap-3 flex-1 max-w-2xl">
          <div className="relative group flex-1">
            <Search size={16} className="absolute left-4 top-1/2 -translate-y-1/2 text-slate-400 group-focus-within:text-[var(--gr-primary)] transition-colors" />
            <input 
              type="text" 
              placeholder="Busque por nome, CPF ou placa..." 
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="pl-12 pr-4 py-3.5 w-full bg-slate-50 dark:bg-slate-900/50 border border-slate-200 dark:border-white/5 rounded-[24px] text-xs focus:outline-none focus:ring-4 focus:ring-[var(--gr-primary)]/10 focus:border-[var(--gr-primary)] transition-all font-semibold shadow-sm"
            />
            {searchTerm && (
              <button 
                onClick={() => setSearchTerm('')}
                className="absolute right-3 top-1/2 -translate-y-1/2 p-1.5 hover:bg-slate-200 dark:hover:bg-slate-700 rounded-full transition-colors"
              >
                <X size={14} className="text-slate-400" />
              </button>
            )}
          </div>

          <button 
            onClick={() => {
              localStorage.removeItem('info');
              navigate('/plataforma/gr/novo');
            }}
            className="flex items-center gap-2 px-6 py-3.5 bg-[var(--gr-primary)] hover:bg-[var(--gr-primary-dark)] text-white rounded-[24px] font-bold text-[10px] uppercase tracking-widest transition-all shadow-lg shadow-[var(--gr-primary)]/20 hover:scale-[1.02] active:scale-95 whitespace-nowrap"
          >
            <Plus size={16} /> Novo Cadastro
          </button>
        </div>
      </div>

      {/* Registrations Table */}
      <div className="h-[600px] w-full max-w-full overflow-hidden min-w-0">
        <ExcelTable 
          data={filteredData} 
          loading={loading}
          columns={tableColumns}
          onEdit={handleEditRegistration}
          onDelete={(registration) => {
            if (window.confirm(`Deseja realmente excluir o cadastro de ${registration.nome_completo}?`)) {
              grService.archiveDriverRegistration(registration.iddrivers).then(() => {
                toast.success('Cadastro arquivado com sucesso');
                fetchData();

              }).catch((error) => {
                handleGrError(error, 'Erro ao excluir cadastro');
              });
            }
          }}
        />
      </div>

      {/* Registration Details Modal */}
      {selectedCard && (
        <GrRegistrationDetails
          data={selectedCard}
          onClose={() => {
            setSelectedCard(null);
            fetchData();
          }}
          onSave={async (updatedData) => {
            try {
              console.log("GR: Saving simplified registration data:", updatedData);
              const payload = {
                 ...updatedData,
                 grupo: userGroup,
                 base_usuario: userBase || 'Sem resposta',
                 data_envio: new Date().toLocaleDateString('pt-BR').split('/').reverse().join('-') + ' '
              };

              // Standardize payload format (FormData with dados_json)
              const formData = new FormData();
              formData.append('dados_json', JSON.stringify(payload));

              await grService.updateDriverRegistration(formData);
              
              if (updatedData.status_doc_motorista || updatedData.status_doc_carro) {
                  await grService.updateDriverDocStatus({
                    iddrivers: updatedData.iddrivers,
                    status_doc_motorista: updatedData.status_doc_motorista,
                    status_doc_carro: updatedData.status_doc_carro
                  });
              }

              toast.success("Cadastro atualizado com sucesso!");
              fetchData();
              setSelectedCard(null);
            } catch (error) {
               handleGrError(error, "Não foi possível salvar as alterações");
            }
          }}
          onProgressStatus={() => {}}
          onApprove={() => {}}
          onReject={() => {}}
        />
      )}
    </div>
  );
};

export default GrRegistrationsSimplified;
