<script setup>
/**
 * FBA-relabel DIN-A4 report (sales-order edit page, post-completion).
 *
 * pdfmake A4 overview showing which label (barcode + printLabelCode) goes
 * onto which article (SKU / name / qty). Printable on a paper printer
 * (CUST_Printer 'pap') via the existing /api/print/picklist route, or
 * downloadable as PDF.
 */
import { toast } from 'bulma-toast'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  orderId: {
    type: [String, Number],
    default: ''
  },
  documentNo: {
    type: String,
    default: ''
  }
})

const emit = defineEmits(['update:modelValue'])

const { t } = useTranslation()
const { fetchRelabelRows, generateBarcodeDataUrl, buildRelabelReportDoc } = useRelabelDocs()

const rows = ref([])
const loadingRows = ref(false)
const busy = ref(false)

const printers = ref([])
const printerValue = ref('default')
const printOptions = ref('')
const printerOptionsByName = ref({})

const fetchPrinters = async () => {
  try {
    const res = await $fetch('/api/printers', { headers: useRequestHeaders(['cookie']) })
    const recs = Array.isArray(res?.records) ? res.records : []
    const seen = new Set()
    // Paper/A4 printers ('pap') first — the report is DIN A4.
    const sorted = [...recs].sort((a, b) => (a?.printerType === 'pap' ? 0 : 1) - (b?.printerType === 'pap' ? 0 : 1))
    const list = [{ name: 'Standarddrucker (default)', value: 'default' }]
    const optsMap = {}
    let preferred = ''
    for (const r of sorted) {
      const cups = r?.cupsName
      if (!cups || seen.has(cups)) continue
      seen.add(cups)
      const typeTag = r?.printerTypeLabel ? ` · ${r.printerTypeLabel}` : ''
      list.push({ name: `${r.name || cups} (${cups})${typeTag}`, value: cups })
      optsMap[cups] = r?.defaultPrintOptions || ''
      if (r?.isDefault && r?.printerType === 'pap' && !preferred) preferred = cups
    }
    printers.value = list
    printerOptionsByName.value = optsMap
    if (preferred) printerValue.value = preferred
  } catch {
    printers.value = [{ name: 'Standarddrucker (default)', value: 'default' }]
  }
}

watch(printerValue, (v) => {
  printOptions.value = printerOptionsByName.value[v] || ''
})

const loadRows = async () => {
  loadingRows.value = true
  try {
    rows.value = await fetchRelabelRows(props.orderId)
  } catch (e) {
    rows.value = []
    console.error('Failed to load relabel rows:', e)
  }
  loadingRows.value = false
}

watch(() => props.modelValue, (open) => {
  if (open) {
    loadRows()
    fetchPrinters()
  }
})

const close = () => emit('update:modelValue', false)

const stamp = () => new Date().toISOString().replace(/[-:T.]/g, '').slice(0, 14)
const fileName = () => `${props.documentNo || props.orderId}-FBA-RELABEL-REPORT-${stamp()}.pdf`

const buildPdf = async () => {
  const withBarcodes = []
  for (const r of rows.value) {
    withBarcodes.push({ ...r, barcode: await generateBarcodeDataUrl(r.code || '-') })
  }
  return await buildRelabelReportDoc(withBarcodes, props.documentNo)
}

const download = async () => {
  if (!rows.value.length) return
  busy.value = true
  try {
    const pdf = await buildPdf()
    pdf.download(fileName())
    close()
  } catch (err) {
    toast({ message: err?.message || 'PDF generation failed', type: 'is-danger', duration: 3000 })
  } finally {
    busy.value = false
  }
}

const print = async () => {
  if (!rows.value.length) return
  busy.value = true
  try {
    const pdf = await buildPdf()
    pdf.getBase64(async (fileContent) => {
      try {
        const res = await $fetch('/api/print/picklist', {
          method: 'POST',
          headers: useRequestHeaders(['cookie']),
          body: {
            pathName: `relabel-reports/${new Date().getFullYear()}`,
            fileName: fileName(),
            fileContent,
            printer: printerValue.value,
            printOptions: printOptions.value || ''
          }
        })
        if (res?.message === 'success') {
          toast({ message: `Report an ${printerValue.value} gesendet.`, type: 'is-success', duration: 3000 })
          close()
        } else {
          toast({ message: res?.stderr || res?.message || 'Print failed', type: 'is-danger', duration: 4000 })
        }
      } catch (err) {
        toast({ message: err?.message || 'Print failed', type: 'is-danger', duration: 3000 })
      } finally {
        busy.value = false
      }
    })
  } catch (err) {
    toast({ message: err?.message || 'PDF generation failed', type: 'is-danger', duration: 3000 })
    busy.value = false
  }
}
</script>

<template>
  <Teleport to="body">
    <div v-if="modelValue" class="rlr-overlay" @click.self="close">
      <div class="rlr-dialog">
        <h3 class="rlr-title">
          <span class="tf-icon ti ti-file-description ti-sm me-1"></span>
          {{ t?.relabel_report_a4 || 'FBA-Etikettenreport (A4)' }}
        </h3>
        <p class="rlr-sub">{{ documentNo }} — {{ rows.length }} {{ t?.positions || 'Positionen' }}</p>

        <div v-if="loadingRows" class="rlr-loading">…</div>
        <div v-else class="rlr-field">
          <label class="label">{{ t?.printer || 'Drucker' }}</label>
          <div class="select is-fullwidth">
            <select v-model="printerValue">
              <option v-for="p in printers" :key="p.value" :value="p.value">{{ p.name }}</option>
            </select>
          </div>
        </div>

        <div class="rlr-actions">
          <button type="button" class="button" :disabled="busy" @click="close">{{ t?.cancel || 'Abbrechen' }}</button>
          <button type="button" class="button" :class="{ 'is-loading': busy }" :disabled="busy || loadingRows || !rows.length" @click="download">
            <span class="tf-icon ti ti-download ti-xs me-1"></span>
            {{ t?.download || 'Download' }}
          </button>
          <button type="button" class="button is-primary" :class="{ 'is-loading': busy }" :disabled="busy || loadingRows || !rows.length" @click="print">
            <span class="tf-icon ti ti-printer ti-xs me-1"></span>
            {{ t?.print || 'Drucken' }}
          </button>
        </div>
      </div>
    </div>
  </Teleport>
</template>

<!-- Teleported markup — styles must be non-scoped (teleport + scoped CSS is unreliable) -->
<style>
.rlr-overlay {
  position: fixed;
  inset: 0;
  z-index: 10000;
  background: rgba(15, 23, 42, 0.55);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 16px;
}
.rlr-dialog {
  background: var(--theme-bg-primary, #fff);
  color: var(--theme-text-primary, #0f172a);
  border-radius: 12px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
  width: min(480px, 100%);
  padding: 20px 22px;
}
.rlr-title { font-size: 1.1rem; font-weight: 700; display: flex; align-items: center; }
.rlr-sub { font-size: 0.85rem; color: var(--theme-text-secondary, #64748b); margin-bottom: 14px; }
.rlr-field { margin-bottom: 12px; }
.rlr-field .select, .rlr-field select { width: 100%; }
.rlr-loading { text-align: center; padding: 24px; }
.rlr-actions { display: flex; justify-content: flex-end; gap: 10px; margin-top: 16px; }
[data-mode="dark"] .rlr-dialog { background: var(--theme-bg-primary, #1e293b); }
</style>
