import React, { useEffect, useState, useMemo } from 'react';
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogHeader,
    DialogTitle,
} from '@/components/ui/dialog';
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { ScrollArea } from "@/components/ui/scroll-area";
import { AgentDTO, CareerTimelineDTO, AgentStatusHistoryDTO } from '@/types/rh';
import { rhService } from '@/services/rhService';
import { format } from 'date-fns';
import { ptBR } from 'date-fns/locale';
import { Button } from '@/components/ui/button';
import {
    User,
    Briefcase,
    Calendar,
    MapPin,
    CreditCard,
    GraduationCap,
    Activity,
    Info,
    FileText,
    History,
    ClipboardList,
    AlertCircle,
    Printer,
    Landmark,
    ShieldCheck,
    CalendarX2
} from 'lucide-react';
import { useOrgUnits } from '@/hooks/useOrgUnits';
import { usePositions } from '@/hooks/usePositions';
import { salaryService } from '@/services/salaryService';
import { AbsenceList } from './absence/AbsenceList';

interface AgentDetailsModalProps {
    open: boolean;
    onOpenChange: (open: boolean) => void;
    agent: AgentDTO | null;
}

const statusMap: Record<string, { label: string, color: string }> = {
    'ACTIVE': { label: 'Ativo', color: 'bg-green-100 text-green-800 border-green-200' },
    'INACTIVE': { label: 'Inativo', color: 'bg-gray-100 text-gray-800 border-gray-200' },
    'SUSPENDED': { label: 'Suspenso', color: 'bg-orange-100 text-orange-800 border-orange-200' },
    'TERMINATED': { label: 'Desligado', color: 'bg-red-100 text-red-800 border-red-200' }
};

const currencyFormatter = new Intl.NumberFormat('pt-GW', {
    style: 'currency',
    currency: 'XOF',
});

const DetailItem = ({ icon: Icon, label, value, color, printFullWidth }: { icon: React.ElementType, label: string, value: string | number | undefined, color?: string, printFullWidth?: boolean }) => (
    <div className={`flex items-start gap-1 p-3 rounded-lg border bg-white/50 print:bg-transparent print:border-none print:p-0 print:gap-0 print:flex-col print:mb-4 ${printFullWidth ? 'print:w-full' : 'print:w-auto min-w-[150px]'}`}>
        <div className={`p-2 rounded-md ${color || 'bg-primary/10 text-primary'} no-print`}>
            <Icon className="h-4 w-4" />
        </div>
        <div className="print:w-full print:flex print:flex-col print:gap-0">
            <p className="text-[10px] font-bold uppercase text-gray-400 tracking-wider leading-none mb-1 print:text-[8pt] print:text-black print:mb-0.5 print:uppercase print:leading-none print:font-black">{label}</p>
            <div className="text-sm font-semibold text-gray-700 leading-tight print:text-[11pt] print:text-black print:font-medium print:m-0 print:leading-tight print:break-words">
                {value || 'N/A'}
            </div>
        </div>
    </div>
);

export function AgentDetailsModal({ open, onOpenChange, agent }: AgentDetailsModalProps) {
    const [careerHistory, setCareerHistory] = useState<CareerTimelineDTO[]>([]);
    const [statusHistory, setStatusHistory] = useState<AgentStatusHistoryDTO[]>([]);
    const [salaryData, setSalaryData] = useState<{
        categories: Record<string, string>;
        grades: Record<string, string>;
        steps: Record<string, number>;
        gridAmount: number | null;
    }>({ categories: {}, grades: {}, steps: {}, gridAmount: null });

    const { orgUnits } = useOrgUnits({ size: 1000 });
    const { positions } = usePositions({ size: 1000 });

    // Criar mapas com normalização de IDs para garantir correspondência
    const orgUnitMap = useMemo(() => {
        const map: Record<string, string> = {};
        orgUnits.forEach(ou => {
            if (ou.id && ou.name) {
                map[ou.id] = ou.name;
                // Também mapear versão sem hífens para garantir correspondência
                const normalizedId = ou.id.toLowerCase().replace(/-/g, '');
                map[normalizedId] = ou.name;
            }
        });
        return map;
    }, [orgUnits]);

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

    useEffect(() => {
        const loadData = async () => {
            if (agent && open) {
                try {
                    const [historyData, statusHistoryData, allCats] = await Promise.all([
                        rhService.getAgentHistory(agent.id),
                        rhService.getAgentStatusHistory(agent.id),
                        salaryService.getAllCategories()
                    ]);

                    setCareerHistory(historyData);
                    setStatusHistory(statusHistoryData);

                    // Resolve Salary Labels
                    const catMap = Object.fromEntries(allCats.map(c => [c.id, c.name]));
                    let gradeMap: Record<string, string> = {};
                    let stepMap: Record<string, number> = {};

                    const categoryId = agent.salaryCategory || agent.activeContract?.salaryCategory;
                    let gridAmount: number | null = null;

                    if (categoryId) {
                        const grades = await salaryService.getGradesByCategory(categoryId);
                        gradeMap = Object.fromEntries(grades.map(g => [g.id, g.name]));

                        const gradeId = agent.salaryGrade || agent.activeContract?.salaryGrade;
                        if (gradeId) {
                            const steps = await salaryService.getStepsByGrade(gradeId);
                            stepMap = Object.fromEntries(steps.map(s => [s.id, s.stepNumber]));

                            const stepId = agent.salaryStep || agent.activeContract?.salaryStep;
                            if (stepId) {
                                try {
                                    const gridEntries = await salaryService.getGridByStep(stepId);
                                    if (gridEntries && gridEntries.length > 0) {
                                        gridAmount = gridEntries[0].baseAmount;
                                    }
                                } catch (e) {
                                    console.error("Erro ao buscar valor na grade", e);
                                }
                            }
                        }
                    }

                    setSalaryData({
                        categories: catMap,
                        grades: gradeMap,
                        steps: stepMap,
                        gridAmount
                    });

                } catch (error) {
                    console.error("Failed to load details data", error);
                }
            }
        };
        loadData();
    }, [agent, open]);

    if (!agent) return null;

    const renderDetailsContent = () => {
        const contract = agent.activeContract;
        const bankAccount = agent.primaryBankAccount;

        return (
            <div className="space-y-6 pt-0 print:space-y-6 print:w-full print:block">
                {/* 1. SEÇÃO DE IDENTIFICAÇÃO E FOTO */}
                <div className="relative border-b pb-6 print:border-none print:pb-0 print:mb-6 print:w-full print:block page-break-inside-avoid">
                    <div className="print:pr-[180px] space-y-4 print:space-y-4">
                        {/* UI Only Header */}
                        <div className="p-4 rounded-xl bg-primary/5 border border-primary/10 no-print flex items-center gap-4">
                            <div className="h-16 w-16 rounded-full bg-primary/20 flex items-center justify-center text-primary">
                                <User className="h-8 w-8" />
                            </div>
                            <div className="flex-1">
                                <h3 className="text-xl font-black text-gray-900 leading-tight">{agent.fullName}</h3>
                                <div className="flex items-center gap-2 mt-1">
                                    <span className="text-xs font-mono font-bold bg-white px-2 py-0.5 rounded border">ID: {agent.matricula}</span>
                                    <span className={`text-[10px] px-2 py-0.5 rounded-full border font-black uppercase ${statusMap[agent.status]?.color}`}>
                                        {statusMap[agent.status]?.label}
                                    </span>
                                </div>
                            </div>
                        </div>

                        {/* Print Version Name Header - MATCHING IMAGE */}
                        <div className="hidden print:block mb-6">
                            <div className="flex items-start gap-4 mb-2">
                                <div className="w-2.5 h-10 bg-black mt-1" />
                                <h3 className="text-2xl font-black text-black leading-tight uppercase tracking-tight">{agent.fullName}</h3>
                            </div>

                            <div className="flex gap-8 text-[9pt] font-black uppercase text-black">
                                <span>MATRÍCULA: {agent.matricula}</span>
                                <span>NIF: {agent.nif}</span>
                                <span>STATUS: {statusMap[agent.status]?.label}</span>
                            </div>
                        </div>

                        <div className="grid grid-cols-2 gap-4 print:flex print:flex-col print:gap-4 print:w-full">
                            <DetailItem icon={User} label="Nacionalidade" value={agent.nationality} />
                            <DetailItem icon={Calendar} label="Data de Nascimento" value={agent.birthDate ? format(new Date(agent.birthDate), "dd/MM/yyyy") : '-'} />
                        </div>
                    </div>

                    <div className="hidden print:block absolute top-0 right-0">
                        <div className="w-32 h-40 border border-gray-400 rounded-sm flex flex-col items-center justify-center text-gray-400 bg-white uppercase text-[8pt] font-bold text-center p-2 mt-1">
                            FOTOGRAFIA<br />3X4
                        </div>
                    </div>
                </div>

                <div className="hidden print:block border-t border-black mb-6" />

                {/* 2 & 3. IDENTIFICAÇÃO E VÍNCULO */}
                <div className="grid grid-cols-1 md:grid-cols-2 gap-x-8 gap-y-6 print:grid-cols-2 print:gap-x-12 print:gap-y-6 print:w-full page-break-inside-avoid">
                    <div className="space-y-4 print:w-full print:block">
                        <div className="border-b border-black/10 pb-2 mb-2 print:border-black print:pb-1 print:mb-4 font-black text-gray-900 uppercase flex items-center gap-2 print:text-[10pt] print:text-black print:block print:w-full">
                            <Info className="h-3 w-3 no-print" /> IDENTIFICAÇÃO E CONTATOS
                        </div>
                        <div className="grid grid-cols-2 gap-4 print:grid-cols-2 print:gap-4">
                            <DetailItem icon={CreditCard} label="NIF" value={agent.nif} />
                            <DetailItem icon={FileText} label="BI / PASSAPORTE" value={agent.biNumber} />
                        </div>
                        <DetailItem icon={MapPin} label="ENDEREÇO RESIDENCIAL" value={agent.address} printFullWidth />
                        <div className="grid grid-cols-2 gap-4 print:grid-cols-2 print:gap-4">
                            <DetailItem icon={User} label="TELEFONE" value={agent.phone} />
                            <DetailItem icon={User} label="EMAIL INSTITUCIONAL" value={agent.email} />
                        </div>
                    </div>

                    <div className="space-y-4 print:w-full print:block">
                        <div className="border-b border-black/10 pb-2 mb-2 print:border-black print:pb-1 print:mb-4 font-black text-gray-900 uppercase flex items-center gap-2 print:text-[10pt] print:text-black print:block print:w-full">
                            <Briefcase className="h-3 w-3 no-print" /> VÍNCULO E CARREIRA
                        </div>
                        <div className="grid grid-cols-2 gap-4 print:grid-cols-2 print:gap-4">
                            <DetailItem icon={FileText} label="TIPO NOMEAÇÃO" value={agent.appointmentType?.replace(/_/g, ' ')} />
                            <DetailItem icon={Activity} label="SITUAÇÃO FUNCIONAL" value={agent.functionalSituation?.replace(/_/g, ' ')} />
                        </div>
                        <DetailItem 
                            icon={MapPin} 
                            label="UNIDADE ORGÂNICA" 
                            value={(() => {
                                const orgUnitId = contract?.orgUnit || agent.orgUnit;
                                if (!orgUnitId) return 'N/A';
                                // Tentar encontrar no map com o ID original
                                let orgUnitName = orgUnitMap[orgUnitId];
                                // Se não encontrar, tentar com ID normalizado
                                if (!orgUnitName) {
                                    const normalizedId = orgUnitId.toLowerCase().replace(/-/g, '');
                                    orgUnitName = orgUnitMap[normalizedId];
                                }
                                // Se ainda não encontrar, tentar busca case-insensitive
                                if (!orgUnitName) {
                                    const foundKey = Object.keys(orgUnitMap).find(
                                        key => key.toLowerCase().replace(/-/g, '') === orgUnitId.toLowerCase().replace(/-/g, '')
                                    );
                                    if (foundKey) {
                                        orgUnitName = orgUnitMap[foundKey];
                                    }
                                }
                                return orgUnitName || 'N/A';
                            })()} 
                            printFullWidth 
                        />
                        <div className="grid grid-cols-2 gap-4 print:grid-cols-2 print:gap-4">
                            <DetailItem 
                                icon={Briefcase} 
                                label="CARGO / CARGO" 
                                value={(() => {
                                    const positionId = contract?.position || agent.position;
                                    if (!positionId) return 'N/A';
                                    // Tentar encontrar no map com o ID original
                                    let positionName = positionMap[positionId];
                                    // Se não encontrar, tentar com ID normalizado
                                    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];
                                        }
                                    }
                                    return positionName || 'N/A';
                                })()} 
                            />
                            <DetailItem icon={GraduationCap} label="HABILITAÇÃO" value={agent.literaryQualification?.replace(/_/g, ' ')} />
                        </div>
                    </div>
                </div>

                {/* 4. DADOS BANCÁRIOS */}
                <div className="space-y-4 print:w-full print:block pt-2 page-break-inside-avoid">
                    <div className="border-b border-black/10 pb-2 mb-2 print:border-black print:pb-1 print:mb-4 font-black text-gray-900 uppercase flex items-center gap-2 print:text-[10pt] print:text-black print:block print:w-full">
                        <CreditCard className="h-3 w-3 no-print" /> DADOS BANCÁRIOS PARA PAGAMENTO
                    </div>
                    {bankAccount ? (
                        <div className="grid grid-cols-1 md:grid-cols-3 gap-4 print:grid-cols-3 print:gap-4 w-full">
                            <DetailItem icon={Landmark} label="INSTITUIÇÃO BANCÁRIA" value={bankAccount.bank} />
                            <DetailItem icon={ShieldCheck} label="AGÊNCIA / BALCÃO" value={bankAccount.branchCode} />
                            <DetailItem icon={CreditCard} label="Nº DE CONTA" value={bankAccount.accountNumber} />
                        </div>
                    ) : (
                        <div className="p-4 rounded-lg bg-yellow-50 border border-yellow-100 flex items-center gap-3 text-yellow-800 text-xs font-semibold print:border-black/10 print:bg-transparent">
                            <AlertCircle className="h-4 w-4 no-print" />
                            <span>Contas bancárias não domiciliadas para este agente. Pagamento via Tesouraria/Caixa.</span>
                        </div>
                    )}
                </div>

                {/* 5. GRADE SALARIAL E REMUNERAÇÃO */}
                <div className="bg-primary/5 p-4 rounded-xl border border-primary/10 print:bg-white print:p-0 print:border-none print:w-full page-break-inside-avoid">
                    <div className="border-b border-black/10 pb-2 mb-6 print:border-black print:pb-1 print:mb-4">
                        <h4 className="text-xs font-black text-gray-900 uppercase flex items-center gap-2 print:text-[10pt] print:text-black font-black">
                            <CreditCard className="h-3 w-3 no-print" /> GRADE SALARIAL E REMUNERAÇÃO
                        </h4>
                    </div>
                    <div className="grid grid-cols-2 md:grid-cols-4 gap-6 print:grid-cols-4 print:gap-4 print:w-full">
                        <DetailItem icon={Briefcase} label="CATEGORIA SALARIAL" value={salaryData.categories[agent.salaryCategory || ''] || salaryData.categories[contract?.salaryCategory || ''] || '-'} />
                        <DetailItem icon={Activity} label="ESCALÃO" value={salaryData.grades[agent.salaryGrade || ''] || salaryData.grades[contract?.salaryGrade || ''] || '-'} />
                        <DetailItem icon={Activity} label="NÍVEL / STEP" value={salaryData.steps[agent.salaryStep || ''] ? `Escalão ${salaryData.steps[agent.salaryStep || '']}` :
                            salaryData.steps[contract?.salaryStep || ''] ? `Escalão ${salaryData.steps[contract?.salaryStep || '']}` : '-'} />
                        <DetailItem icon={CreditCard} label="SALÁRIO BASE (XOF)" value={contract?.baseSalaryRef ? currencyFormatter.format(contract.baseSalaryRef) :
                            agent.activeContract?.baseSalaryRef ? currencyFormatter.format(agent.activeContract.baseSalaryRef) :
                                salaryData.gridAmount ? currencyFormatter.format(salaryData.gridAmount) : '0,00 FCFA'} />
                    </div>
                </div>

                {/* 6. DATAS ADMINISTRATIVAS E DEPENDENTES */}
                <div className="grid grid-cols-2 md:grid-cols-4 gap-6 border-t pt-8 border-black/10 print:grid-cols-4 print:border-none print:mt-4 print:pt-0 print:w-full page-break-inside-avoid">
                    <DetailItem icon={Calendar} label="DATA ADMISSÃO" value={agent.hireDate ? format(new Date(agent.hireDate), "dd/MM/yyyy") : '-'} />
                    <DetailItem icon={Calendar} label="DATA DE POSSE" value={agent.posseDate ? format(new Date(agent.posseDate), "dd/MM/yyyy") : '-'} />
                    <DetailItem icon={User} label="DEPENDENTES" value={agent.eligibleDependentsCount || '0'} />
                    <DetailItem icon={Briefcase} label="VÍNCULO" value={contract?.contractType?.replace(/_/g, ' ') || 'N/A'} />
                </div>

                {/* 7. REFERÊNCIA LEGAL (APENAS IMPRESSÃO) */}
                {contract?.legalActReference && (
                    <div className="hidden print:block border-t border-black pt-4 mt-4 page-break-inside-avoid">
                        <p className="text-[8pt] font-black text-black uppercase tracking-tight">SUPORTE LEGAL / REFERÊNCIA DE DESPACHO</p>
                        <p className="text-[10pt] font-medium italic text-black mt-1">"{contract.legalActReference}"</p>
                    </div>
                )}

                {/* 8. ASSINATURAS (APENAS IMPRESSÃO) */}
                <div className="hidden print:flex justify-between items-start mt-24 px-4 w-full page-break-inside-avoid">
                    <div className="text-center w-[250px] flex flex-col items-center">
                        <p className="text-[8pt] font-black uppercase mb-16 italic text-black/40">ASSINATURA DO AGENTE</p>
                        <div className="border-t border-black w-full mb-1"></div>
                        <p className="text-[10pt] font-black uppercase text-black">{agent.fullName}</p>
                        <p className="text-[7pt] text-black/60 uppercase font-black mt-0.5">Agente Público</p>
                    </div>

                    <div className="text-center w-[250px] flex flex-col items-center">
                        <p className="text-[8pt] font-black uppercase mb-16 italic text-black/40">HOMOLOGAÇÃO / RH</p>
                        <div className="border-t border-black w-full mb-1"></div>
                        <p className="text-[10pt] font-black uppercase text-black">Direção de Recursos Humanos</p>
                        <p className="text-[7pt] text-black/60 uppercase font-black mt-0.5">Ministério da Administração Pública</p>
                    </div>
                </div>
            </div>
        );
    };

    const renderTimeline = () => {
        // Ordenar por data (ascendente) caso o backend não tenha ordenado corretamente
        const sortedHistory = [...careerHistory].sort((a, b) => {
            try {
                return new Date(a.date).getTime() - new Date(b.date).getTime();
            } catch {
                return 0;
            }
        });

        return (
            <ScrollArea className="h-[500px] w-full rounded-md border p-4 bg-gray-50/30 mt-4 print:h-auto print:border-none print:p-0">
                {sortedHistory.length === 0 ? (
                    <div className="flex flex-col items-center justify-center py-12 text-center">
                        <History className="h-12 w-12 text-gray-200 mb-2" />
                        <p className="text-gray-500 font-medium">Nenhum evento de vida laboral registrado.</p>
                        <p className="text-xs text-gray-400 mt-2">Os eventos de carreira aparecerão aqui conforme forem registrados.</p>
                    </div>
                ) : (
                    <div className="relative border-l-2 border-primary/20 ml-2 pl-6 space-y-8 my-4 print:border-black/20 print:ml-4">
                        {sortedHistory.map((record, index) => {
                            // Validar e formatar data
                            let formattedDate = 'Data inválida';
                            try {
                                formattedDate = format(new Date(record.date), "dd 'de' MMMM 'de' yyyy", { locale: ptBR });
                            } catch (e) {
                                console.warn('Erro ao formatar data do evento:', record.date, e);
                                formattedDate = record.date || 'Data não disponível';
                            }

                            // Verificar se há split remunerativo válido
                            const hasValidSplit = record.cargoAmount !== undefined && record.cargoAmount !== null &&
                                                 record.exercicioAmount !== undefined && record.exercicioAmount !== null;

                            return (
                                <div key={`${record.date}-${index}`} className="relative">
                                    <span className="absolute -left-[31px] top-1 h-4 w-4 rounded-full border-2 border-primary bg-white ring-4 ring-white print:border-black print:ring-transparent" />
                                    <div className="flex flex-col space-y-2 bg-white p-4 rounded-xl border shadow-sm hover:shadow-md transition-shadow print:border-black/10 print:shadow-none print:p-2">
                                        <div className="flex justify-between items-start">
                                            <div className="flex flex-col flex-1">
                                                <span className="font-bold text-base text-primary uppercase tracking-tight print:text-black print:text-sm">
                                                    {record.eventTypeName || record.eventType || 'Evento'}
                                                </span>
                                                <span className="text-xs text-gray-400 font-medium print:text-[9px] print:text-black/60 mt-1">
                                                    {formattedDate}
                                                </span>
                                                {record.reason && (
                                                    <span className="text-xs text-gray-500 italic mt-1 print:text-[9px] print:text-black/70">
                                                        {record.reason}
                                                    </span>
                                                )}
                                            </div>
                                            {record.totalBaseAmount && record.totalBaseAmount > 0 && (
                                                <div className="text-right bg-green-50 px-3 py-1 rounded-lg border border-green-100 print:bg-transparent print:border-none ml-4">
                                                    <p className="text-[10px] text-green-700 font-bold uppercase print:text-[8px] print:text-black">vencimento base</p>
                                                    <p className="text-sm font-black text-green-900 print:text-xs print:text-black">
                                                        {currencyFormatter.format(record.totalBaseAmount)}
                                                    </p>
                                                </div>
                                            )}
                                        </div>

                                        <div className={`grid ${hasValidSplit ? 'grid-cols-2' : 'grid-cols-1'} gap-4 py-2 border-y border-gray-50 print:border-black/10`}>
                                            <div>
                                                <p className="text-[10px] text-gray-400 font-bold uppercase print:text-[8px]">Referência Legal</p>
                                                <p className="text-xs font-semibold text-gray-700 print:text-[9px] print:text-black">
                                                    {record.documentRef || "N/A"}
                                                </p>
                                            </div>
                                            {hasValidSplit && (
                                                <div>
                                                    <p className="text-[10px] text-gray-400 font-bold uppercase print:text-[8px]">Split Remunerativo (5/6 | 1/6)</p>
                                                    <div className="flex flex-col gap-1 text-[11px] font-bold print:text-[9px]">
                                                        <span className="text-blue-700 print:text-black">
                                                            Cargo (5/6): {currencyFormatter.format(record.cargoAmount || 0)}
                                                        </span>
                                                        <span className="text-orange-700 print:text-black">
                                                            Exercício (1/6): {currencyFormatter.format(record.exercicioAmount || 0)}
                                                        </span>
                                                    </div>
                                                </div>
                                            )}
                                        </div>

                                        {record.changeSummary && (
                                            <div className="bg-blue-50/50 p-2 rounded-md border-l-4 border-blue-200 print:bg-transparent print:border-l-2 print:border-black/20">
                                                <p className="text-[11px] text-blue-800 leading-relaxed italic print:text-[9px] print:text-black">
                                                    {record.changeSummary}
                                                </p>
                                            </div>
                                        )}
                                    </div>
                                </div>
                            );
                        })}
                    </div>
                )}
            </ScrollArea>
        );
    };

    const renderStatusHistory = () => {
        const parseDate = (dateStr: string) => {
            try {
                return format(new Date(dateStr), "dd/MM/yyyy HH:mm");
            } catch (e) {
                return dateStr;
            }
        };

        return (
            <ScrollArea className="h-[500px] w-full rounded-md border p-4 bg-gray-50/30 mt-4 print:h-auto">
                {statusHistory.length === 0 ? (
                    <div className="flex flex-col items-center justify-center py-12 text-center">
                        <ClipboardList className="h-12 w-12 text-gray-200 mb-2" />
                        <p className="text-gray-500 font-medium">Nenhum histórico de edições registrado.</p>
                    </div>
                ) : (
                    <div className="space-y-4">
                        {statusHistory.map((h, index) => (
                            <div key={index} className="bg-white p-4 rounded-xl border shadow-sm hover:border-primary/30 transition-colors print:shadow-none print:border-black/10 print:p-2">
                                <div className="flex justify-between items-start mb-2">
                                    <div className="flex items-center gap-2">
                                        <div className="p-1.5 bg-gray-100 rounded-md no-print">
                                            <Activity className="h-4 w-4 text-gray-500" />
                                        </div>
                                        <div>
                                            <span className="text-sm font-bold text-gray-900 block leading-tight print:text-xs">
                                                {h.eventType === 'EDIT' ? 'Edição Cadastral' : h.eventType}
                                            </span>
                                            <span className="text-[10px] text-gray-400 uppercase font-bold print:text-[8px] print:text-black/60">
                                                {parseDate(h.changedAt)} • Por: {h.changedBy || 'Sistema'}
                                            </span>
                                        </div>
                                    </div>
                                    {h.newStatus !== h.previousStatus && (
                                        <span className="text-[10px] px-2 py-0.5 rounded-full bg-blue-50 text-blue-700 border border-blue-100 font-bold uppercase print:bg-transparent print:border-black/20 print:text-black">
                                            Status: {h.newStatus}
                                        </span>
                                    )}
                                </div>

                                {h.changeLog && (
                                    <div className="mt-2 p-3 bg-slate-50 rounded-lg border border-slate-100 print:bg-transparent print:border-black/10 print:p-1">
                                        <p className="text-xs text-slate-600 leading-relaxed font-medium print:text-[9px] print:text-black">
                                            <span className="text-primary/70 mr-1 font-bold tracking-tight no-print">Alterações:</span>
                                            {h.changeLog}
                                        </p>
                                    </div>
                                )}

                                {h.reason && (
                                    <div className="mt-2 flex items-start gap-2 text-xs text-blue-700 bg-blue-50/50 p-2 rounded border border-blue-100 print:bg-transparent print:border-black/10 print:p-1">
                                        <AlertCircle className="h-3.5 w-3.5 mt-0.5 no-print" />
                                        <p className="print:text-[9px] print:text-black"><strong>Justificativa:</strong> {h.reason}</p>
                                    </div>
                                )}
                            </div>
                        ))}
                    </div>
                )}
            </ScrollArea>
        );
    };

    return (
        <Dialog open={open} onOpenChange={onOpenChange}>
            <DialogContent className="sm:max-w-5xl max-h-[95vh] overflow-y-auto border-none shadow-2xl p-0 print:max-h-none print:overflow-visible print:w-full print:max-w-none print:shadow-none print:static print:transform-none">
                <style dangerouslySetInnerHTML={{
                    __html: `
                @media print {
                    @page { size: A4; margin: 10mm 15mm; }
                    
                    /* Force everything to visible and flow naturally */
                    body, html { 
                        overflow: visible !important; 
                        height: auto !important; 
                        background: white !important; 
                        -webkit-print-color-adjust: exact !important; 
                        print-color-adjust: exact !important; 
                    }

                    /* Hide all UI elements except the active dialog */
                    body > *:not([role="dialog"]) { display: none !important; }
                    [data-state="closed"] { display: none !important; }
                    
                    /* Reset Dialog and Content constraints */
                    [role="dialog"] {
                        position: absolute !important;
                        top: 0 !important;
                        left: 0 !important;
                        transform: none !important;
                        width: 100% !important;
                        max-width: none !important;
                        height: auto !important;
                        max-height: none !important;
                        overflow: visible !important;
                        padding: 0 !important;
                        margin: 0 !important;
                        background: white !important;
                        box-shadow: none !important;
                        border: none !important;
                        display: block !important;
                    }

                    .no-print { display: none !important; }
                    .print-only { display: block !important; }
                    
                    /* Force ScrollArea and other containers to release content */
                    [data-radix-scroll-area-viewport] {
                        overflow: visible !important;
                        height: auto !important;
                    }

                    * { 
                        color: black !important; 
                        border-color: black !important; 
                        -webkit-print-color-adjust: exact !important;
                        print-color-adjust: exact !important;
                    }
                    
                    .page-break-inside-avoid { 
                        page-break-inside: avoid !important;
                        break-inside: avoid !important;
                    }

                    /* Specific fix for the top header position */
                    .print-header-container {
                        position: relative !important;
                        top: 0 !important;
                        width: 100% !important;
                        display: block !important;
                    }
                }
            ` }} />

                <div className="bg-primary h-2 w-full absolute top-0 left-0 no-print" />

                {/* Print Header - ISOLATED FOR BETTER RENDERING */}
                <div className="hidden print:block w-full print-header-container">
                    {/* Top Top Bar */}
                    <div className="flex justify-between items-center px-8 border-b border-black py-2 mb-6">
                        <span className="text-[9pt] font-black uppercase">Ficha Individual do Agente Público</span>
                        <div className="flex items-center gap-2">
                            <span className="text-[9pt] font-bold">Data de Emissão: {format(new Date(), 'dd/MM/yyyy')}</span>
                        </div>
                    </div>

                    <div className="px-8 pb-4 flex flex-col items-center text-center">
                        <div className="flex items-center justify-center w-full mb-6 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 text-center leading-none">ESCUDO DA REPÚBLICA</span>
                            </div>
                            <div className="flex flex-col items-center">
                                <h1 className="text-md font-black uppercase tracking-widest text-black leading-tight">República da Guiné-Bissau</h1>
                                <p className="text-[9pt] font-bold text-black uppercase">Ministério da Administração Pública, Trabalho e Segurança Social</p>
                                <p className="text-[8.5pt] font-bold text-black 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>
                </div>

                <div className="p-6 print:p-8 pt-0">
                    <DialogHeader className="mb-4 no-print pt-6">
                        <div className="flex justify-between items-start">
                            <div>
                                <DialogTitle className="text-2xl font-black text-primary uppercase flex items-center gap-2">
                                    <FileText className="h-6 w-6" /> Detalhes do Funcionário
                                </DialogTitle>
                                <DialogDescription className="font-medium text-gray-500">
                                    Ficha individual, vida laboral e histórico completo de auditoria.
                                </DialogDescription>
                            </div>
                            <Button
                                variant="outline"
                                size="sm"
                                onClick={() => window.print()}
                                className="flex items-center gap-2"
                            >
                                <Printer className="h-4 w-4" />
                                Imprimir
                            </Button>
                        </div>
                    </DialogHeader>

                    <Tabs defaultValue="details" className="w-full">
                        <TabsList className="grid w-full grid-cols-4 bg-gray-100 p-1 rounded-xl no-print">
                            <TabsTrigger value="details" className="rounded-lg data-[state=active]:bg-white data-[state=active]:shadow-sm">
                                <Info className="h-3.5 w-3.5 mr-2" /> Ficha
                            </TabsTrigger>
                            <TabsTrigger value="history" className="rounded-lg data-[state=active]:bg-white data-[state=active]:shadow-sm" title="Vida Laboral (Boletim Oficial)">
                                <History className="h-3.5 w-3.5 mr-2" /> Vida Laboral
                            </TabsTrigger>
                            <TabsTrigger value="absences" className="rounded-lg data-[state=active]:bg-white data-[state=active]:shadow-sm">
                                <CalendarX2 className="h-3.5 w-3.5 mr-2" /> Faltas
                            </TabsTrigger>
                            <TabsTrigger value="status_history" className="rounded-lg data-[state=active]:bg-white data-[state=active]:shadow-sm">
                                <ClipboardList className="h-3.5 w-3.5 mr-2" /> Log Edições
                            </TabsTrigger>
                        </TabsList>

                        <div className="print:block">
                            <TabsContent value="details" className="print:block print:!visible">
                                {renderDetailsContent()}
                            </TabsContent>

                            <TabsContent value="history" className="print:block print:!visible">
                                {renderTimeline()}
                            </TabsContent>

                            <TabsContent value="absences" className="print:block print:!visible">
                                <AbsenceList agentId={agent.id} />
                            </TabsContent>

                            <TabsContent value="status_history" className="print:block print:!visible">
                                {renderStatusHistory()}
                            </TabsContent>
                        </div>
                    </Tabs>
                </div>
            </DialogContent>
        </Dialog>
    );
}
