import { date } from 'alga-js'
import { toast } from 'bulma-toast'

/**
 * DHL Transportversicherung feedback shared by the three commissioning surfaces
 * (desktop page, commission modal, mobile page):
 *  - `dhlInsurancePreview(order)`  → banner data BEFORE the label is created
 *  - `handleDhlInsuranceResult()`  → toasts + prints the "Nur DHL Filiale" hint
 *    label(s) returned by commission/parcels/dhl/{index,multi} (`res.insurance`).
 * Thresholds mirror server/utils/dhlInsurance.ts.
 */
export const useDhlInsuranceFeedback = () => {
  const fmt = (v: any) => (Number(v) || 0).toLocaleString('de-DE', { minimumFractionDigits: 0, maximumFractionDigits: 2 }) + ' €'

  const dhlInsurancePreview = (order: any) => {
    if (!order || (order.isDHLTransportInsurance ?? order.IsDHLTransportInsurance) !== true) return null
    const total = Number(order.GrandTotal ?? order.grandTotal ?? 0)
    const tier = total <= 500 ? null : total <= 2500 ? 'A' : 'B'
    const capped = total > 25000
    let text: string
    if (!tier) text = `Transportversicherung gewünscht – Auftragswert ${fmt(total)} liegt in der DHL-Haftung (500 €), es wird nichts gebucht.`
    else if (tier === 'A') text = `Transportversicherung A wird gebucht (${fmt(total)}, bis 2.500 €) – Paket darf in die DHL-Abholung.`
    else if (!capped) text = `Transportversicherung B wird gebucht (${fmt(total)}, bis 25.000 €) – NUR DHL FILIALE, nicht in die Abholung!`
    else text = `Auftragswert ${fmt(total)} über dem DHL-Maximum – nur bis 25.000 € versicherbar. NUR DHL FILIALE, Rücksprache nötig!`
    return { total, tier, capped, filialeOnly: tier === 'B', text }
  }

  const handleDhlInsuranceResult = (res: any, opts: {
    print: (content: any) => any
    printer: string
    userName?: string
    startDelayMs?: number
  }) => {
    const ins = res?.insurance
    if (!ins || !ins.requested) return
    if (ins.message) {
      const severe = !ins.booked || ins.filialeOnly || ins.capped
      toast({
        message: (ins.booked ? '🛡️ ' : '⚠️ ') + ins.message,
        type: !ins.booked ? 'is-warning' : (severe ? 'is-danger' : 'is-info'),
        duration: severe ? 15000 : 6000
      })
    }
    const hints: { b64: string; shipmentNo: string }[] = []
    if (ins.hintLabelB64) hints.push({ b64: ins.hintLabelB64, shipmentNo: res?.dhl_parcel?.shipmentNo || 'shipment' })
    for (const p of ins.parcels || []) {
      if (p?.hintLabelB64) hints.push({ b64: p.hintLabelB64, shipmentNo: p.shipmentNo || `P${p.index}` })
    }
    if (!hints.length) return
    const stamp = date.now().replace(/\-|\:/g, '_').replace(' ', '-')
    hints.forEach((h, i) => {
      setTimeout(() => {
        opts.print({
          pathName: `label/${new Date().getFullYear()}/insurance`,
          fileName: `${stamp}-${h.shipmentNo}-DHL-FILIALE-${opts.userName || 'SUPERUSER'}.pdf`,
          fileContent: h.b64,
          shippingPrinter: opts.printer
        })
      }, (opts.startDelayMs || 0) + i * 500)
    })
    toast({
      message: `${hints.length} Hinweis-Etikett(en) "NUR DHL FILIALE" gedruckt – bitte aufs Paket kleben.`,
      type: 'is-danger',
      duration: 12000
    })
  }

  return { dhlInsurancePreview, handleDhlInsuranceResult }
}
