"use client";

import { useState } from "react";

import JsBarcode from "jsbarcode";
import QRCode from "qrcode";

type PrintableLotLabel = {
  lotId: string;
  lotCode: string;
  qrValue?: string | null;
  barcodeValue?: string | null;
  supplier: string;
  grade: string;
  warehouse: string;
  location: string;
  receivedAt: string;
  status: string;
};

type LotLabelPrintButtonProps = {
  lot: PrintableLotLabel;
  className?: string;
  label?: string;
};

function escapeHtml(value: string) {
  return value
    .replaceAll("&", "&amp;")
    .replaceAll("<", "&lt;")
    .replaceAll(">", "&gt;")
    .replaceAll('"', "&quot;")
    .replaceAll("'", "&#39;");
}

function formatDate(value: string) {
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return "-";
  return date.toLocaleDateString("id-ID");
}

function buildBarcodeSvg(value: string) {
  const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
  JsBarcode(svg, value, {
    format: "CODE128",
    displayValue: false,
    margin: 0,
    width: 1.5,
    height: 44
  });

  svg.setAttribute("width", "100%");
  svg.setAttribute("height", "52");
  svg.setAttribute("preserveAspectRatio", "none");

  return svg.outerHTML;
}

function buildPrintHtml({
  lot,
  qrDataUrl,
  barcodeSvg,
  qrValue,
  barcodeValue
}: {
  lot: PrintableLotLabel;
  qrDataUrl: string;
  barcodeSvg: string;
  qrValue: string;
  barcodeValue: string;
}) {
  const safeLotCode = escapeHtml(lot.lotCode);
  const safeSupplier = escapeHtml(lot.supplier);
  const safeGrade = escapeHtml(lot.grade);
  const safeWarehouse = escapeHtml(lot.warehouse);
  const safeLocation = escapeHtml(lot.location);
  const safeStatus = escapeHtml(lot.status);
  const safeReceivedAt = escapeHtml(formatDate(lot.receivedAt));
  const safeQrValue = escapeHtml(qrValue);
  const safeBarcodeValue = escapeHtml(barcodeValue);

  return `<!doctype html>
<html lang="id">
  <head>
    <meta charset="utf-8" />
    <title>Cetak Label ${safeLotCode}</title>
    <style>
      :root {
        color-scheme: light;
      }
      body {
        margin: 0;
        background: #f3f5f6;
        color: #191c1d;
        font-family: Arial, Helvetica, sans-serif;
      }
      .sheet {
        padding: 16px;
      }
      .label {
        width: 100mm;
        min-height: 50mm;
        margin: 0 auto;
        background: #fff;
        border: 1px solid #d7dfe1;
        border-radius: 10px;
        padding: 8px;
        box-shadow: 0 10px 25px rgba(15, 23, 42, 0.08);
      }
      .header {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        gap: 12px;
      }
      .eyebrow {
        margin: 0 0 3px;
        color: #5d6b72;
        font-size: 8px;
        font-weight: 700;
        letter-spacing: 0.08em;
        text-transform: uppercase;
      }
      .lot-code {
        margin: 0;
        font-size: 16px;
        line-height: 1;
        font-weight: 800;
        word-break: break-word;
      }
      .status {
        display: inline-flex;
        align-items: center;
        border-radius: 999px;
        background: #dff7ef;
        color: #0f766e;
        padding: 3px 8px;
        font-size: 9px;
        font-weight: 700;
      }
      .grid {
        display: grid;
        grid-template-columns: 34mm 1fr;
        gap: 8px;
        margin-top: 8px;
      }
      .qr-box {
        border: 1px solid #d7dfe1;
        border-radius: 8px;
        padding: 6px;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        min-height: 0;
      }
      .qr-box img {
        width: 28mm;
        height: 28mm;
      }
      .meta {
        display: grid;
        gap: 4px;
      }
      .meta-card {
        border: 1px solid #d7dfe1;
        border-radius: 8px;
        padding: 5px 6px;
      }
      .meta-label {
        margin: 0 0 2px;
        color: #5d6b72;
        font-size: 8px;
        font-weight: 700;
        letter-spacing: 0.06em;
        text-transform: uppercase;
      }
      .meta-value {
        margin: 0;
        font-size: 10px;
        line-height: 1.15;
        font-weight: 600;
        word-break: break-word;
      }
      .barcode {
        margin-top: 8px;
        border: 1px solid #d7dfe1;
        border-radius: 8px;
        padding: 6px 8px;
      }
      .barcode-svg {
        height: 52px;
      }
      .scan-value {
        margin: 4px 0 0;
        text-align: center;
        font-size: 9px;
        font-weight: 700;
        letter-spacing: 0.04em;
        word-break: break-all;
      }
      .footer {
        margin-top: 6px;
        display: grid;
        gap: 2px;
      }
      .footer-line {
        margin: 0;
        color: #5d6b72;
        font-size: 8px;
      }
      @media print {
        body {
          background: #fff;
        }
        .sheet {
          padding: 0;
        }
        .label {
          width: auto;
          min-height: auto;
          border: 0;
          border-radius: 0;
          box-shadow: none;
          margin: 0;
        }
        @page {
          size: 100mm 50mm;
          margin: 2mm;
        }
      }
    </style>
  </head>
  <body>
    <main class="sheet">
      <section class="label">
        <div class="header">
          <div>
            <p class="eyebrow">AbelBirdnest Stock Label</p>
            <h1 class="lot-code">${safeLotCode}</h1>
          </div>
          <span class="status">${safeStatus}</span>
        </div>
        <div class="grid">
          <div class="qr-box">
            <img src="${qrDataUrl}" alt="QR ${safeLotCode}" />
            <p class="scan-value">${safeQrValue}</p>
          </div>
          <div class="meta">
            <div class="meta-card">
              <p class="meta-label">Agen</p>
              <p class="meta-value">${safeSupplier}</p>
            </div>
            <div class="meta-card">
              <p class="meta-label">Item</p>
              <p class="meta-value">${safeGrade}</p>
            </div>
            <div class="meta-card">
              <p class="meta-label">Gudang</p>
              <p class="meta-value">${safeWarehouse}</p>
            </div>
            <div class="meta-card">
              <p class="meta-label">Lokasi</p>
              <p class="meta-value">${safeLocation}</p>
            </div>
          </div>
        </div>
        <div class="barcode">
          <div class="barcode-svg">${barcodeSvg}</div>
          <p class="scan-value">${safeBarcodeValue}</p>
        </div>
        <div class="footer">
          <p class="footer-line">Tanggal terima: ${safeReceivedAt}</p>
          <p class="footer-line">QR dan barcode mengarah ke nilai scan yang dapat dipakai untuk lookup detail lot.</p>
        </div>
      </section>
    </main>
    <script>
      window.addEventListener("load", () => {
        window.focus();
        window.print();
      });
    </script>
  </body>
</html>`;
}

export function LotLabelPrintButton({
  lot,
  className = "ops-btn-primary",
  label = "Cetak Label"
}: LotLabelPrintButtonProps) {
  const [printing, setPrinting] = useState(false);

  async function handlePrint() {
    setPrinting(true);
    const printWindow = window.open("", "_blank", "width=980,height=760");

    if (!printWindow) {
      setPrinting(false);
      window.alert("Popup cetak diblokir browser. Izinkan pop-up untuk situs ini lalu coba lagi.");
      return;
    }

    try {
      printWindow.document.open();
      printWindow.document.write(`<!doctype html><html><head><title>Menyiapkan Label</title></head><body style="font-family: Arial, sans-serif; padding: 24px;">Menyiapkan label cetak...</body></html>`);
      printWindow.document.close();

      const response = await fetch(`/api/v1/lots/${lot.lotId}/print-label`, {
        method: "POST",
        headers: { "Content-Type": "application/json" }
      });
      const payload =
        (await response.json()) as
          | {
              data: {
                printable_label: {
                  lot_id: string;
                  lot_code: string;
                  qr_value: string;
                  barcode_value: string;
                  supplier: string;
                  grade: string;
                  warehouse: string;
                  location: string;
                  received_at: string;
                  status: string;
                };
              };
            }
          | { message?: string };

      if (!response.ok || !("data" in payload)) {
        throw new Error(("message" in payload && payload.message) || "Gagal mencatat cetak label.");
      }

      const printableLabel = payload.data.printable_label;
      const qrValue = printableLabel.qr_value;
      const barcodeValue = printableLabel.barcode_value;
      const qrDataUrl = await QRCode.toDataURL(qrValue, {
        width: 160,
        margin: 1,
        errorCorrectionLevel: "M"
      });

      const barcodeSvg = buildBarcodeSvg(barcodeValue);

      printWindow.document.open();
      printWindow.document.write(
        buildPrintHtml({
          lot: {
            lotId: printableLabel.lot_id,
            lotCode: printableLabel.lot_code,
            qrValue,
            barcodeValue,
            supplier: printableLabel.supplier,
            grade: printableLabel.grade,
            warehouse: printableLabel.warehouse,
            location: printableLabel.location,
            receivedAt: printableLabel.received_at,
            status: printableLabel.status
          },
          qrDataUrl,
          barcodeSvg,
          qrValue,
          barcodeValue
        })
      );
      printWindow.document.close();
    } catch (error) {
      if (!printWindow.closed) {
        printWindow.close();
      }
      window.alert(error instanceof Error ? error.message : "Gagal menyiapkan label cetak.");
    } finally {
      setPrinting(false);
    }
  }

  return (
    <button type="button" onClick={() => void handlePrint()} className={className} disabled={printing}>
      {printing ? "Menyiapkan label..." : label}
    </button>
  );
}
