/**
 * Shared logic for the FBA-relabel print surfaces on the sales-order edit page
 * (label print modal + DIN-A4 report modal).
 *
 * Rows come from the order's lines: every active product line with its
 * printLabelCode (the alternative barcode Amazon requires), SKU, name and qty.
 * Barcodes are generated CLIENT-side as PNG data URLs (jsbarcode, CODE128) and
 * embedded by the server / pdfmake — the server never generates barcodes
 * (same split as the receipt label printing).
 */

import { loadPdfMake } from '~/utils/loadPdfMake'

export interface RelabelRow {
  line: string | number
  sku: string
  upc: string
  product: string
  code: string
  qty: number
}

export const useRelabelDocs = () => {
  const fetchRelabelRows = async (orderId: any): Promise<RelabelRow[]> => {
    const res: any = await $fetch(`/api/orders/${orderId}/order-line`, {
      headers: useRequestHeaders(['cookie'])
    })
    return (res?.records || [])
      .filter((item: any) => item?.IsActive !== false && item?.M_Product_ID?.id && Number(item?.QtyEntered || 0) > 0)
      .map((item: any) => ({
        line: item?.Line || '',
        sku: item?.M_Product_ID?.SKU || item?.M_Product_ID?.Value || '',
        // iDempiere stores UPC and EAN in one field (UPC, labeled "UPC/EAN"); UPC2 = second barcode
        upc: item?.M_Product_ID?.UPC || item?.M_Product_ID?.UPC2 || '',
        product: item?.M_Product_ID?.Name || item?.M_Product_ID?.identifier || '',
        code: String(item?.printLabelCode ?? item?.PrintLabelCode ?? '').trim(),
        qty: Number(item?.QtyEntered || 0)
      }))
      .sort((a: any, b: any) => Number(a.line) - Number(b.line))
  }

  const generateBarcodeDataUrl = async (code: string): Promise<string> => {
    const JsBarcode = (await import('jsbarcode')).default
    const { createCanvas } = await import('canvas')
    const canvasElem = createCanvas()
    JsBarcode(canvasElem, code, {
      format: 'CODE128',
      lineColor: '#000',
      displayValue: false,
      margin: 0
    })
    return canvasElem.toDataURL()
  }

  /**
   * DIN-A4 report: which label (barcode + code) goes onto which article (SKU).
   * Rows must already carry `barcode` (PNG data URL from generateBarcodeDataUrl).
   */
  const buildRelabelReportDoc = async (rows: Array<RelabelRow & { barcode: string }>, documentNo: string) => {
    const pdfMake = await loadPdfMake()

    const tableBody: any[] = [[
      { text: 'Pos.', style: 'th' },
      { text: 'SKU', style: 'th' },
      { text: 'EAN/UPC', style: 'th' },
      { text: 'Artikel', style: 'th' },
      { text: 'Etiketten-Code (FBA)', style: 'th' },
      { text: 'Menge', style: 'th', alignment: 'right' }
    ]]
    for (const r of rows) {
      tableBody.push([
        { text: String(r.line), margin: [0, 8, 0, 0] },
        { text: r.sku, bold: true, margin: [0, 8, 0, 0] },
        { text: r.upc || '-', margin: [0, 8, 0, 0] },
        { text: r.product, margin: [0, 8, 0, 0] },
        {
          stack: [
            { image: r.barcode, width: 150, height: 34 },
            { text: r.code, bold: true, fontSize: 9, margin: [0, 2, 0, 0] }
          ],
          margin: [0, 4, 0, 4]
        },
        { text: String(r.qty), alignment: 'right', bold: true, margin: [0, 8, 0, 0] }
      ])
    }
    const totalQty = rows.reduce((acc, r) => acc + Number(r.qty || 0), 0)
    tableBody.push([
      { text: '', colSpan: 4 }, {}, {}, {},
      { text: 'Etiketten gesamt', bold: true, alignment: 'right', margin: [0, 4, 0, 0] },
      { text: String(totalQty), bold: true, alignment: 'right', margin: [0, 4, 0, 0] }
    ])

    const docDefinition: any = {
      pageSize: 'A4',
      pageMargins: [40, 50, 40, 50],
      content: [
        { text: `FBA-Relabel – Auftrag ${documentNo || ''}`, fontSize: 15, bold: true },
        { text: 'Übersicht: welches Etikett auf welchen Artikel (SKU) geklebt wird.', fontSize: 9, color: '#555555', margin: [0, 3, 0, 4] },
        // Amazon FBA labeling rules (official "How to label products" guide)
        { text: 'Wichtig (Amazon-Vorgaben): Original-Barcode (EAN/UPC) vollständig überkleben. Label nicht auf Kanten, Ecken oder Rundungen kleben — ca. 6 mm Abstand zum Verpackungsrand einhalten.', fontSize: 9, bold: true, color: '#b45309', margin: [0, 0, 0, 12] },
        {
          table: {
            headerRows: 1,
            widths: [24, 76, 74, '*', 152, 34],
            body: tableBody
          },
          layout: {
            hLineColor: () => '#cccccc',
            vLineColor: () => '#cccccc',
            hLineWidth: () => 0.5,
            vLineWidth: () => 0.5
          }
        },
        { text: `Erstellt: ${new Date().toLocaleString('de-DE', { timeZone: 'Europe/Berlin' })}`, fontSize: 8, color: '#777777', margin: [0, 10, 0, 0] }
      ],
      styles: {
        th: { bold: true, fontSize: 9, fillColor: '#f0f0f0', margin: [0, 2, 0, 2] }
      },
      defaultStyle: { fontSize: 9 }
    }

    return pdfMake.createPdf(docDefinition)
  }

  return { fetchRelabelRows, generateBarcodeDataUrl, buildRelabelReportDoc }
}
