import React, { useState, useCallback, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { Search, Loader2, ArrowLeft, ArchiveRestore } from 'lucide-react';
import ExcelTable from '../components/ExcelTable';
import { toast } from 'sonner';
import { handleGrError } from '../utils/grErrorHandler';
import * as grService from '../services/grService';



const ArchivedContractsView = () => {
  const navigate = useNavigate();
  const [searchTerm, setSearchTerm] = useState('');
  const [loading, setLoading] = useState(true);
  const [data, setData] = useState([]);
  const [bases, setBases] = useState([]);

  const fetchData = useCallback(async () => {
    setLoading(true);
    try {
      const [resp, basesResp, regResp] = await Promise.all([
        grService.getArchivedContracts(),
        grService.getBases(),
        grService.getAllDriverRegistrations() // Fetch registrations to map names/CPFs
      ]);
      const list = resp.Base_Dados_API ?? resp.dados ?? resp.data ?? resp;
      const basesList = basesResp.Base_Dados_API || basesResp.dados || basesResp || [];
      const registrations = regResp.dados || regResp.Base_Dados_API || regResp || [];
      
      const enhancedList = (Array.isArray(list) ? list : []).map(contract => {
        const driver = Array.isArray(registrations) ? registrations.find(d => d.iddrivers === contract.iddrivers) : null;
        return {
          ...contract,
          nome: driver ? driver.nome_completo : contract.nome_completo || '-',
          nome_completo: contract.nome_completo || driver?.nome_completo || '-',
          cpf: driver?.cpf || contract.cpf || '-',
        };
      });

      setData(enhancedList);
      setBases(Array.isArray(basesList) ? basesList : []);
    } catch (error) {
      handleGrError(error, "Erro ao carregar contratos arquivados.");
      setData([]);
    } finally {
      setLoading(false);
    }
  }, []);

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

  const filteredData = React.useMemo(() => {
    if (!data.length) return [];
    const q = searchTerm.trim().toLowerCase();
    if (!q) return data;
    return data.filter(
      (r) =>
        (r.nome_completo ?? '').toLowerCase().includes(q) ||
        (r.nome ?? '').toLowerCase().includes(q) ||
        (r.cpf ?? '').toString().includes(searchTerm)
    );
  }, [data, searchTerm]);

  const handleUnarchive = async (idcontrato_drivers) => {
    try {
      await grService.unarchiveContract(idcontrato_drivers);
      toast.success('Contrato desarquivado com sucesso!');
      fetchData();
    } catch (error) {
      handleGrError(error, "Erro ao desarquivar o contrato.");
    }
  };

  const columns = [
    { field: 'nome', header: 'Nome', width: 220 },
    { field: 'cpf', header: 'CPF', width: 140 },
    { field: 'base_driver', header: 'Base', width: 150 },
    { field: 'tipo_contract', header: 'Tipo', width: 120 },
    { field: 'data_admissao', header: 'Admissão', width: 120 },
    { field: 'data_demissao', header: 'Demissão', width: 120 },
    { field: 'status_assinatura', header: 'Assinatura', width: 130 },
    { field: 'status', header: 'Status', width: 100 },
    {
      field: 'global_status',
      header: 'Status Global',
      width: 180,
      render: (row) => (
        <span
          className={`px-3 py-1 rounded-full text-[10px] font-bold uppercase tracking-wider ${
            row.global_status === 'Assinado' || row.global_status === 'Assinados'
              ? 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400'
              : row.global_status === 'Não Assinado'
              ? 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400'
              : 'bg-slate-100 text-slate-700 dark:bg-slate-700 dark:text-slate-300'
          }`}
        >
          {row.global_status ?? '-'}
        </span>
      ),
    },
    {
      field: 'actions',
      header: 'Ações',
      width: 100,
      render: (row) => (
        <div className="flex items-center justify-center">
          <button
            onClick={() => handleUnarchive(row.idcontrato_drivers || row.iddrivers)}
            title="Desarquivar"
            className="p-2 text-slate-400 hover:text-emerald-500 transition-colors"
          >
            <ArchiveRestore size={18} />
          </button>
        </div>
      )
    }
  ];

  return (
    <div className="flex flex-col h-full gap-4 md:gap-8">
      <div className="flex flex-col gap-6">
        <div className="flex flex-col xl:flex-row xl:items-end justify-between gap-8">
          <div className="space-y-1">
            <h1 className="text-3xl md:text-5xl font-bold text-slate-800 dark:text-white tracking-tighter leading-none">
              Contratos <span className="text-[var(--gr-primary)]">Arquivados</span>
            </h1>
            <p className="text-slate-400 dark:text-slate-500 text-sm md:text-base font-medium italic opacity-80">
              Itens arquivados da gestão de contratos
            </p>
          </div>
          <div className="flex flex-wrap items-center gap-4">
            <button
              type="button"
              onClick={() => navigate('/plataforma/gr/contratos')}
              className="flex items-center gap-2 px-6 py-3 bg-slate-100 dark:bg-slate-800 hover:bg-slate-200 dark:hover:bg-slate-700 text-slate-700 dark:text-slate-200 rounded-[24px] font-bold text-[11px] uppercase tracking-widest transition-all"
            >
              <ArrowLeft size={16} />
              Voltar aos Contratos
            </button>
            <div className="relative flex-1 min-w-[260px] max-w-[400px]">
              <Search
                size={16}
                className="absolute left-4 top-1/2 -translate-y-1/2 text-slate-400"
              />
              <input
                type="text"
                placeholder="Buscar por nome ou CPF..."
                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 font-semibold focus:outline-none focus:ring-4 focus:ring-[var(--gr-primary)]/10 focus:border-[var(--gr-primary)]"
              />
            </div>
          </div>
        </div>
      </div>

      <div className="flex-1 min-h-0 bg-white dark:bg-black/20 rounded-[32px] border border-slate-100 dark:border-white/5 overflow-hidden shadow-sm">
        {loading ? (
          <div className="flex h-full w-full items-center justify-center">
            <Loader2 className="animate-spin text-[var(--gr-primary)]" size={32} />
          </div>
        ) : (
          <div className="h-[600px] w-full max-w-full overflow-hidden min-w-0">
            <ExcelTable
              data={filteredData}
              columns={columns}
              rowKey="iddrivers"
              pageSize={10}
              loading={false}
              filterDefs={[
                { field: 'base_driver', header: 'Base', type: 'select' },
                { field: 'tipo_contract', header: 'Tipo', type: 'select' },
                { field: 'status_assinatura', header: 'Assinatura', type: 'select' },
                { field: 'global_status', header: 'Status Global', type: 'select' }
              ]}
              filterOptions={{
                base_driver: bases.map(b => b.base || b.nome).filter(Boolean).sort()
              }}
            />
          </div>
        )}
      </div>
    </div>
  );
};

export default ArchivedContractsView;
