import jsPDF from 'jspdf';
import autoTable from 'jspdf-autotable';
import * as XLSX from 'xlsx';
import { format } from 'date-fns';
import { SalaryGradeDTO, SalaryStepDTO, SalaryGridDTO } from '@/types/salary';

// Copied/Adapted type from SalaryStructurePage to ensure compatibility
export interface ExportableSalaryRow {
    grade: SalaryGradeDTO;
    categoryName: string;
    steps: {
        step: SalaryStepDTO;
        currentValue: number | null;
        gridEntry: SalaryGridDTO | null;
    }[];
}

export const exportSalaryToExcel = (rows: ExportableSalaryRow[], filename: string = 'grelha_salarial.xlsx') => {
    // 1. Flatten Data
    // We determine the max number of steps to create columns dynamically or just list them

    const flattenedData = rows.map(row => {
        const baseObject: any = {
            'Código': row.grade.code,
            'Cargo/Função': row.grade.name,
            'Categoria': row.categoryName,
        };

        // Add steps dynamically
        row.steps.forEach(stepDetails => {
            const stepNum = stepDetails.step.stepNumber;
            baseObject[`Step ${stepNum}`] = stepDetails.currentValue || 0;
        });

        return baseObject;
    });

    // 2. Create Sheet
    const worksheet = XLSX.utils.json_to_sheet(flattenedData);
    const workbook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(workbook, worksheet, 'Grelha Salarial');

    // 3. Auto-width columns
    const wscols = Object.keys(flattenedData[0] || {}).map(key => {
        return { wch: Math.max(key.length, 15) }; // min width 15
    });
    worksheet['!cols'] = wscols;

    // 4. Download
    XLSX.writeFile(workbook, filename);
};

export const exportSalaryToPDF = (rows: ExportableSalaryRow[], filename: string = 'grelha_salarial.pdf') => {
    const doc = new jsPDF('l', 'mm', 'a4'); // Landscape for better width

    // Title
    doc.setFontSize(16);
    doc.text('Tabela Salarial - OGE 2025', 14, 15);

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

    // Prepare Headers & Body
    // We need to normalize columns. Let's assume max 10 steps for PDF readable width, or just key ones.
    // For simplicity, let's show up to Step 5, or dynamic.

    // Find absolute max steps to define columns
    const maxSteps = rows.reduce((max, row) => Math.max(max, row.steps.length), 0);

    const headRow = ['Código', 'Cargo', 'Categoria'];
    for (let i = 1; i <= maxSteps; i++) {
        headRow.push(`S${i}`); // Compact header
    }

    const bodyData = rows.map(row => {
        const rowData = [
            row.grade.code,
            row.grade.name,
            row.categoryName
        ];

        // Fill steps, pad with empty if missing
        for (let i = 1; i <= maxSteps; i++) {
            const step = row.steps.find(s => s.step.stepNumber === i);
            rowData.push(step && step.currentValue ? step.currentValue.toLocaleString('pt-AO') : '-');
        }
        return rowData;
    });

    autoTable(doc, {
        head: [headRow],
        body: bodyData,
        startY: 28,
        styles: { fontSize: 8 },
        headStyles: { fillColor: [59, 130, 246] },
        theme: 'grid'
    });

    doc.save(filename);
};
