import jsPDF from 'jspdf';
import autoTable from 'jspdf-autotable';
import * as XLSX from 'xlsx';
import { AgentDTO } from '@/types/rh';
import { format } from 'date-fns';

export const exportAgentsToPDF = (agents: AgentDTO[], filename: string = 'agentes.pdf') => {
    const doc = new jsPDF();

    // Título
    doc.setFontSize(16);
    doc.text('Lista de Agentes', 14, 15);

    // Data de geração
    doc.setFontSize(10);
    doc.text(`Gerado em: ${format(new Date(), 'dd/MM/yyyy HH:mm')}`, 14, 22);

    // Tabela
    const tableData = agents.map(agent => [
        agent.matricula,
        agent.fullName,
        agent.nif,
        agent.primaryBankAccount?.bank || '-',
        agent.primaryBankAccount?.accountNumber || '-',
        agent.status,
    ]);

    autoTable(doc, {
        head: [['Matrícula', 'Nome', 'NIF', 'Banco', 'Nº Conta', 'Status']],
        body: tableData,
        startY: 28,
        styles: { fontSize: 8 },
        headStyles: { fillColor: [59, 130, 246] }
    });

    doc.save(filename);
};

export const exportAgentsToExcel = (agents: AgentDTO[], filename: string = 'agentes.xlsx') => {
    const data = agents.map(agent => ({
        'Matrícula': agent.matricula,
        'Nome Completo': agent.fullName,
        'NIF': agent.nif,
        'BI': agent.biNumber,
        'Status': agent.status,
        'Situação Funcional': agent.functionalSituation?.replace(/_/g, ' '),
        'Tipo de Nomeação': agent.appointmentType?.replace(/_/g, ' '),
        'Data Admissão': agent.hireDate ? format(new Date(agent.hireDate), 'dd/MM/yyyy') : '',
        'Data Posse': agent.posseDate ? format(new Date(agent.posseDate), 'dd/MM/yyyy') : '',
        'Telefone': agent.phone || '',
        'Email': agent.email || '',
        'Banco': agent.primaryBankAccount?.bank || '',
        'Conta Bancária': agent.primaryBankAccount?.accountNumber || '',
        'IBAN': agent.primaryBankAccount?.iban || ''
    }));

    const worksheet = XLSX.utils.json_to_sheet(data);
    const workbook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(workbook, worksheet, 'Agentes');

    // Ajustar largura das colunas
    const maxWidth = 50;
    const wscols = Object.keys(data[0] || {}).map(() => ({ wch: maxWidth }));
    worksheet['!cols'] = wscols;

    XLSX.writeFile(workbook, filename);
};

export const printAgentsList = () => {
    window.print();
};
