import { NextResponse } from 'next/server';
import * as XLSX from 'xlsx';

export async function GET() {
  try {
    const wb = XLSX.utils.book_new();

    // Headers exactos del formato FedEx (FEDEX 08-FEBRERO-2026.xlsx)
    const headers = [
      'AWB', 'MASTER', 'Sale Value', 'Orddate', 'Shipto', 'Shipto2',
      'Address', 'Address2', 'City', 'State', 'Zip', 'Phone',
      'Soldto', 'Soldto2', 'STPhone', 'Ponumber', 'CUSTnbr',
      'SHIPDT', 'Deliver', 'Quantity', 'Item', 'ProdDesc',
      'Length', 'Width', 'Height', 'WeightKg', 'DclValue',
      'Message', 'Service', 'PkgType', 'GenDesc', 'ShipCtry',
      'Currency', 'Origin', 'UOM', 'TPComp', 'TPAttn', 'TPAdd1',
      'TPCity', 'TPState', 'TPCtry', 'TPZip', 'TPPhone', 'TPAcct',
      'Farm', 'MSG', 'TRACKING', 'OBSERVACIONES'
    ];

    // Row de ejemplo
    const exampleRow = [
      '023-0103 4795', '4715 3336 2988', 135, '2026-02-08',
      'David Moore', '',
      '6524 Rockrose Trail', '', 'Fort Worth', 'TX', '76123', '817-228-0276',
      'David Moore', '', '817-228-0276', '5188', '5188',
      'SABADO/VUELO MARTES/ENTREGA JUEVES', '2026-02-12', 1, '1137452', 'Delphinium Sky Blue 80cm PK70',
      90, 28, 17, 7.14, 56,
      '', 'ES', 'CP', 'Delphinium Sky Blue 80cm PK70', 'US',
      'USD', 'EC', 'BOX', 'EBLOOMS FARM DIRECT INC.', 'Janpaul Sanchez', '20980 SW 234TH ST',
      'HOMESTEAD', 'FL', 'US', '33031', '786-749-4338', '9Y68W4',
      'FLORES MAGICAS', 'N', '', ''
    ];

    const wsData = [headers, exampleRow];
    const ws = XLSX.utils.aoa_to_sheet(wsData);

    // Anchos de columna
    ws['!cols'] = headers.map((h, i) => {
      const widths: Record<string, number> = {
        'AWB': 16, 'MASTER': 16, 'Sale Value': 12, 'Orddate': 14,
        'Shipto': 22, 'Shipto2': 16, 'Address': 28, 'Address2': 18,
        'City': 16, 'State': 8, 'Zip': 8, 'Phone': 14,
        'Soldto': 22, 'Soldto2': 16, 'STPhone': 14,
        'Ponumber': 12, 'CUSTnbr': 12, 'SHIPDT': 34, 'Deliver': 14,
        'Quantity': 10, 'Item': 14, 'ProdDesc': 36, 'Length': 8,
        'Width': 8, 'Height': 8, 'WeightKg': 10, 'DclValue': 10,
        'Message': 20, 'Service': 8, 'PkgType': 8, 'GenDesc': 36,
        'ShipCtry': 8, 'Currency': 8, 'Origin': 8, 'UOM': 8,
        'TPComp': 28, 'TPAttn': 22, 'TPAdd1': 24, 'TPCity': 14,
        'TPState': 8, 'TPCtry': 8, 'TPZip': 10, 'TPPhone': 14,
        'TPAcct': 10, 'Farm': 22, 'MSG': 6, 'TRACKING': 18, 'OBSERVACIONES': 18,
      };
      return { wch: widths[h] || 12 };
    });

    XLSX.utils.book_append_sheet(wb, ws, 'FedEx_Import');

    // Hoja de instrucciones
    const instrData = [
      ['INSTRUCCIONES — FORMATO FEDEX US FLORAL'],
      [''],
      ['Campos clave:'],
      ['Ponumber', 'PO# de la orden (número de compra del cliente)'],
      ['CUSTnbr', 'Order Number (número de orden del cliente, puede ser igual al Ponumber)'],
      ['Item', 'Código del producto (hasta 14 caracteres)'],
      ['ProdDesc / GenDesc', 'Descripción del producto (máx. 35 caracteres para FedEx)'],
      ['Quantity', 'Número de cajas (1 fila = 1 tipo de producto, Quantity = cajas de ese producto)'],
      ['DclValue', 'Valor declarado en USD por caja'],
      ['WeightKg', 'Peso en kilogramos por caja'],
      ['TRACKING', 'Se llena DESPUÉS del procesamiento FedEx — dejar vacío al importar'],
      [''],
      ['Campos de tercero pagador (TP*): datos de EBLOOMS FARM DIRECT INC.'],
      ['TPComp', 'EBLOOMS FARM DIRECT INC.'],
      ['TPAdd1', '20980 SW 234TH ST'],
      ['TPCity', 'HOMESTEAD'], ['TPState', 'FL'], ['TPCtry', 'US'],
      ['TPZip', '33031'], ['TPPhone', '786-749-4338'], ['TPAcct', '9Y68W4'],
    ];
    const wsInstr = XLSX.utils.aoa_to_sheet(instrData);
    wsInstr['!cols'] = [{ wch: 20 }, { wch: 60 }];
    XLSX.utils.book_append_sheet(wb, wsInstr, 'Instrucciones');

    const buffer = XLSX.write(wb, { type: 'buffer', bookType: 'xlsx' });

    return new Response(buffer, {
      headers: {
        'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        'Content-Disposition': 'attachment; filename="FORMATO_FEDEX_USFLORAL.xlsx"',
      },
    });
  } catch (e) {
    console.error(e);
    return NextResponse.json({ error: 'Error generating template' }, { status: 500 });
  }
}
