import { useState, useMemo } from 'react';
import { format } from 'date-fns';
import { Plus, Edit, MoreVertical, Trash2, Users, UserCheck, UserX, Clock, Eye, FileDown, Printer, Filter } from 'lucide-react';
import { PageHeader } from '@/components/common/PageHeader';
import { ServerDataTable } from '@/components/common/ServerDataTable';
import { Button } from '@/components/ui/button';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
  DropdownMenuSeparator,
} from '@/components/ui/dropdown-menu';
import { useAgents } from '@/hooks/useAgents';
import { useOrgUnits } from '@/hooks/useOrgUnits';
import { usePositions } from '@/hooks/usePositions';
import { useMinistries } from '@/hooks/useMinistries';
import { AgentDTO } from '@/types/rh';
import { useToast } from '@/hooks/use-toast';
import { AgentFormModal } from '../components/AgentFormModal';
import { AgentWizardModal } from '../components/AgentWizardModal';
import { AgentDetailsModal } from '../components/AgentDetailsModal';
import { ImportAgentsModal } from '../components/ImportAgentsModal';
import { AgentFilterPanel } from '../components/AgentFilterPanel';
import { ConfirmDialog } from '@/components/common/ConfirmDialog';
import { StatsCard } from '@/components/common/StatsCard';
import { formatNumber } from '@/utils/locale';
import { exportAgentsToPDF, exportAgentsToExcel, printAgentsList } from '@/utils/exportUtils';

export function AgentsPage() {
  const [selectedAgent, setSelectedAgent] = useState<AgentDTO | null>(null);
  const [isFormOpen, setIsFormOpen] = useState(false);
  const [isWizardOpen, setIsWizardOpen] = useState(false);
  const [isImportOpen, setIsImportOpen] = useState(false);
  const [isDetailsOpen, setIsDetailsOpen] = useState(false);
  const [isDeleteOpen, setIsDeleteOpen] = useState(false);
  const [filters, setFilters] = useState<{
    query?: string;
    status?: string;
    ministry?: string;
    orgUnit?: string;
    position?: string;
    functionalSituation?: string;
    appointmentType?: string;
  }>({});
  const [showFilters, setShowFilters] = useState(false);
  const { toast } = useToast();

  const {
    agents,
    loading,
    page,
    totalPages,
    totalElements,
    stats: backendStats,
    setPage,
    createAgent,
    updateAgent,
    deleteAgent,
    fetchAgents
  } = useAgents({
    page: 0,
    size: 20,
    sortBy: 'fullName',
    sortDirection: 'ASC',
    ...filters
  });

  // Fetch lookups for display
  const { orgUnits } = useOrgUnits({ size: 1000 });
  const { positions } = usePositions({ size: 1000 });
  const { ministries } = useMinistries({ size: 100 });

  const orgUnitMap = useMemo(() => {
    const map: Record<string, string> = {};
    orgUnits.forEach(ou => map[ou.id] = ou.name);
    return map;
  }, [orgUnits]);

  const positionMap = useMemo(() => {
    const map: Record<string, string> = {};
    positions.forEach(pos => {
      if (pos.id && pos.title) {
        // Normalizar IDs para garantir correspondência (remover hífens se necessário)
        const normalizedId = pos.id.toLowerCase().replace(/-/g, '');
        map[pos.id] = pos.title;
        map[normalizedId] = pos.title; // Também mapear versão sem hífens
      }
    });
    return map;
  }, [positions]);

  // Os agentes já vêm filtrados do backend via useAgents que usa os filters
  const filteredAgents = agents;

  // Use backend stats if available, otherwise fallback (though now backend stats should be available)
  const stats = backendStats || {
    total: totalElements,
    active: 0,
    inactive: 0,
    terminated: 0,
    suspended: 0
  };

  const handleCreate = () => {
    setSelectedAgent(null);
    setIsFormOpen(true);
  };

  const handleEdit = (agent: AgentDTO) => {
    setSelectedAgent(agent);
    setIsFormOpen(true);
  };

  const handleOpenDetails = (agent: AgentDTO) => {
    setSelectedAgent(agent);
    setIsDetailsOpen(true);
  };

  const handleDelete = (agent: AgentDTO) => {
    setSelectedAgent(agent);
    setIsDeleteOpen(true);
  };

  const handleDeleteConfirm = async () => {
    if (!selectedAgent) return;
    try {
      await deleteAgent(selectedAgent.id);
      toast({
        title: 'Sucesso',
        description: 'Funcionário excluído com sucesso',
      });
      setIsDeleteOpen(false);
      setSelectedAgent(null);
    } catch (err: any) {
      toast({
        title: 'Erro',
        description: err.message || 'Erro ao excluir funcionário',
        variant: 'destructive',
      });
    }
  };

  const handleFormSubmit = async (data: any) => {
    try {
      if (selectedAgent) {
        await updateAgent(selectedAgent.id, data);
        toast({
          title: 'Sucesso',
          description: 'Funcionário atualizado com sucesso',
        });
      } else {
        await createAgent(data);
        toast({
          title: 'Sucesso',
          description: 'Funcionário cadastrado com sucesso',
        });
      }
      setIsFormOpen(false);
      setSelectedAgent(null);
      fetchAgents();
    } catch (err: any) {
      toast({
        title: 'Erro',
        description: err.message || 'Erro ao salvar funcionário',
        variant: 'destructive',
      });
    }
  };

  const columns = [
    {
      key: 'matricula',
      header: 'Matrícula',
      cell: (agent: AgentDTO) => <span className="font-mono">{agent.matricula}</span>,
    },
    {
      key: 'fullName',
      header: 'Nome',
      cell: (agent: AgentDTO) => agent.fullName,
    },
    {
      key: 'nif',
      header: 'NIF',
      cell: (agent: AgentDTO) => agent.nif,
    },
    {
      key: 'biNumber',
      header: 'BI',
      cell: (agent: AgentDTO) => agent.biNumber,
    },
    {
      key: 'position',
      header: 'Cargo',
      cell: (agent: AgentDTO) => {
        // Priorizar cargo do contrato ativo, caso contrário usar do agente
        const positionId = agent.activeContract?.position || agent.position;
        if (!positionId) {
          return '-';
        }
        
        // Tentar encontrar no map com o ID original
        let positionName = positionMap[positionId];
        
        // Se não encontrar, tentar com ID normalizado (sem hífens)
        if (!positionName) {
          const normalizedId = positionId.toLowerCase().replace(/-/g, '');
          positionName = positionMap[normalizedId];
        }
        
        // Se ainda não encontrar, tentar busca case-insensitive
        if (!positionName) {
          const foundKey = Object.keys(positionMap).find(
            key => key.toLowerCase().replace(/-/g, '') === positionId.toLowerCase().replace(/-/g, '')
          );
          if (foundKey) {
            positionName = positionMap[foundKey];
          }
        }
        
        if (!positionName) {
          // Se ainda não encontrou, retornar o ID truncado para debug
          return positionId.substring(0, 8) + '...';
        }
        
        return positionName;
      },
    },
    {
      key: 'orgUnit',
      header: 'Unidade',
      cell: (agent: AgentDTO) => {
        // Priorizar unidade do contrato ativo, caso contrário usar do agente
        const orgUnitId = agent.activeContract?.orgUnit || agent.orgUnit;
        return orgUnitId ? (orgUnitMap[orgUnitId] || '...') : '-';
      },
    },
    {
      key: 'status',
      header: 'Status',
      cell: (agent: AgentDTO) => {
        const statusMap: Record<string, string> = {
          ACTIVE: 'Ativo',
          INACTIVE: 'Inativo',
          SUSPENDED: 'Suspenso',
          TERMINATED: 'Desligado'
        };
        return (
          <span className={`px-2 py-1 rounded-full text-xs font-semibold
                        ${agent.status === 'ACTIVE' ? 'bg-green-100 text-green-800' :
              agent.status === 'TERMINATED' ? 'bg-red-100 text-red-800' :
                'bg-gray-100 text-gray-800'}`}>
            {statusMap[agent.status] || agent.status}
          </span>
        );
      },
    },
    {
      key: 'actions',
      header: 'Ações',
      className: 'no-print w-10',
      cell: (agent: AgentDTO) => (
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button variant="ghost" size="sm">
              <MoreVertical className="h-4 w-4" />
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end">
            <DropdownMenuItem onClick={() => handleOpenDetails(agent)}>
              <Eye className="mr-2 h-4 w-4" />
              Detalhes
            </DropdownMenuItem>
            <DropdownMenuItem onClick={() => handleEdit(agent)}>
              <Edit className="mr-2 h-4 w-4" />
              Editar
            </DropdownMenuItem>
            <DropdownMenuItem
              onClick={() => handleDelete(agent)}
              className="text-destructive"
            >
              <Trash2 className="mr-2 h-4 w-4" />
              Excluir
            </DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      ),
    },
  ];

  const isAnyModalOpen = isFormOpen || isDetailsOpen || isDeleteOpen;

  return (
    <div className={`space-y-6 print:space-y-0 ${isAnyModalOpen ? 'print:hidden' : ''}`}>
      <style dangerouslySetInnerHTML={{
        __html: `
                @media print {
                    @page { size: A4 portrait; margin: 10mm 15mm; }
                    
                    body, html { 
                        overflow: visible !important; 
                        height: auto !important; 
                        background: white !important; 
                        -webkit-print-color-adjust: exact !important; 
                        print-color-adjust: exact !important; 
                    }

                    /* Hide UI elements */
                    .no-print, 
                    .gov-card > div:first-child, /* Search/Actions bar in ServerDataTable */
                    .gov-card > div:last-child /* Pagination in ServerDataTable */
                    { display: none !important; }

                    /* Reset container constraints and remove SHADOWS */
                    .gov-card, .overflow-x-auto, [class*="shadow"] {
                        overflow: visible !important;
                        border: none !important;
                        box-shadow: none !important;
                        padding: 0 !important;
                        margin: 0 !important;
                        background: transparent !important;
                    }

                    table {
                        width: 100% !important;
                        border-collapse: collapse !important;
                        page-break-inside: auto;
                        box-shadow: none !important;
                        border: 1px solid black !important; /* Professional border for the whole table */
                    }

                    tr { 
                        page-break-inside: avoid; 
                        page-break-after: auto;
                        box-shadow: none !important;
                        background: transparent !important;
                    }
                    
                    thead { display: table-header-group; }
                    tfoot { display: table-footer-group; }

                    th {
                        background-color: #f3f4f6 !important;
                        color: black !important;
                        font-weight: bold !important;
                        border: 1px solid black !important;
                        padding: 8px 4px !important;
                        text-align: left !important;
                        font-size: 8pt !important;
                        text-transform: uppercase !important;
                        box-shadow: none !important;
                    }

                    td {
                        border: 1px solid black !important;
                        padding: 8px 4px !important;
                        font-size: 8pt !important;
                        color: black !important;
                        box-shadow: none !important;
                    }

                    * { 
                        box-shadow: none !important;
                        -webkit-print-color-adjust: exact !important;
                        print-color-adjust: exact !important;
                    }
                }
            ` }} />

      {/* Professional Institutional Print Header */}
      <div className="hidden print:block w-full">
        {/* Top Info Bar */}
        <div className="flex justify-between items-center border-b border-black py-2 mb-6 text-[9pt] font-black uppercase">
          <span>Lista Nominal de Agentes Públicos</span>
          <span>Data de Emissão: {format(new Date(), 'dd/MM/yyyy')}</span>
        </div>

        {/* Institutional Identity */}
        <div className="flex flex-col items-center text-center mb-8">
          <div className="flex items-center justify-center w-full mb-4 gap-8">
            <div className="w-16 h-16 border border-black rounded-full flex items-center justify-center p-1">
              <span className="text-[5pt] font-black leading-none uppercase">Escudo da República</span>
            </div>
            <div className="flex flex-col items-center">
              <h1 className="text-md font-black uppercase tracking-widest leading-tight">República da Guiné-Bissau</h1>
              <p className="text-[9pt] font-bold uppercase">Ministério da Administração Pública, Trabalho e Segurança Social</p>
              <p className="text-[8.5pt] font-bold uppercase border-t border-black pt-0.5 mt-0.5 px-4">Direção Geral da Função Pública</p>
            </div>
            <div className="w-16 h-16 opacity-0"></div> {/* Spacer */}
          </div>
          <div className="w-full h-1 bg-black mb-1"></div>
          <div className="w-full h-[1px] bg-black"></div>
        </div>
      </div>

      <div className="no-print">
        <PageHeader
          title="Gestão de Funcionários"
          description="Cadastro e manutenção de agentes públicos"
        />
      </div>

      <div className="flex items-center justify-between gap-4 no-print">
        <div className="flex gap-2">
          <Button variant="outline" size="sm" onClick={() => setShowFilters(!showFilters)}>
            <Filter className="h-4 w-4 mr-1" />
            Filtros
          </Button>
          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <Button variant="outline" size="sm">
                <FileDown className="h-4 w-4 mr-1" />
                Exportar
              </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent className="no-print">
              <DropdownMenuItem onClick={() => exportAgentsToPDF(agents)}>
                <FileDown className="h-4 w-4 mr-2" />
                PDF
              </DropdownMenuItem>
              <DropdownMenuItem onClick={() => exportAgentsToExcel(agents)}>
                <FileDown className="h-4 w-4 mr-2" />
                Excel
              </DropdownMenuItem>
              <DropdownMenuItem onClick={printAgentsList}>
                <Printer className="h-4 w-4 mr-2" />
                Imprimir
              </DropdownMenuItem>
            </DropdownMenuContent>
          </DropdownMenu>
        </div>
      </div>

      {showFilters && (
        <AgentFilterPanel
          initialFilters={filters}
          onApply={(newFilters) => {
            setFilters(newFilters);
            setPage(0);
          }}
          onClear={() => {
            setFilters({});
            setPage(0);
          }}
          ministries={ministries.map(m => ({ id: m.id, name: m.name }))}
          orgUnits={orgUnits.map(ou => ({ id: ou.id, name: ou.name }))}
          positions={positions.map(pos => ({ id: pos.id, name: pos.title }))}
        />
      )}

      {/* Stats - Hidden on print for a cleaner list view */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4 no-print">
        <StatsCard
          title="Total de Agentes"
          value={formatNumber(stats.total, 0)}
          icon={Users}
        />
        <StatsCard
          title="Activos"
          value={formatNumber(stats.active, 0)}
          icon={UserCheck}
        />
        <StatsCard
          title="Inactivos/Suspensos"
          value={formatNumber(stats.inactive + ((stats as any).suspended || 0), 0)}
          icon={UserX}
        />
        <StatsCard
          title="Desligados"
          value={formatNumber(stats.terminated, 0)}
          icon={Clock}
        />
      </div>

      <div className="flex items-center justify-end gap-4 no-print">
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button>
              <Plus className="mr-2 h-4 w-4" />
              Novo Funcionário
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end">
            <DropdownMenuItem onClick={() => setIsWizardOpen(true)}>
              <Plus className="mr-2 h-4 w-4" />
              Cadastro Completo (Agente + Contrato + Conta)
            </DropdownMenuItem>
            <DropdownMenuSeparator />
            <DropdownMenuItem onClick={() => setIsImportOpen(true)}>
              <FileDown className="mr-2 h-4 w-4" />
              Importar Excel (Lote)
            </DropdownMenuItem>
            <DropdownMenuSeparator />
            <DropdownMenuItem onClick={handleCreate}>
              Cadastro Simples (Apenas Agente)
            </DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      </div>

      <ServerDataTable
        data={filteredAgents}
        columns={columns}
        loading={loading}
        page={page}
        totalPages={totalPages}
        totalElements={totalElements}
        pageSize={20}
        onPageChange={setPage}
        onSearch={(val) => setFilters(prev => ({ ...prev, query: val }))}
        searchPlaceholder="Pesquisar por nome ou matrícula..."
        emptyMessage="Nenhum funcionário encontrado"
      />

      <AgentWizardModal
        open={isWizardOpen}
        onOpenChange={(open) => {
          setIsWizardOpen(open);
          if (!open) {
            fetchAgents();
          }
        }}
        onComplete={() => {
          fetchAgents();
        }}
      />

      <AgentFormModal
        open={isFormOpen}
        onOpenChange={(open) => {
          setIsFormOpen(open);
          if (!open) setSelectedAgent(null);
        }}
        agent={selectedAgent}
        onSubmit={handleFormSubmit}
      />

      <AgentDetailsModal
        open={isDetailsOpen}
        onOpenChange={(open) => {
          setIsDetailsOpen(open);
          if (!open) setSelectedAgent(null);
        }}
        agent={selectedAgent}
      />

      {isImportOpen && (
        <ImportAgentsModal
          onClose={() => setIsImportOpen(false)}
          onSuccess={() => fetchAgents()}
        />
      )}

      <ConfirmDialog
        open={isDeleteOpen}
        onOpenChange={setIsDeleteOpen}
        title="Excluir Funcionário"
        description={`Tem certeza que deseja excluir o funcionário "${selectedAgent?.fullName}"?`}
        onConfirm={handleDeleteConfirm}
      />
    </div>
  );
}
