"use client";

// ═══════════════════════════════════════════════════════════════
//  Checklist PDF preview — styled EXACTLY like the QRS NC
//  (Corrective & Preventive Action) template: logo header table,
//  #adcff6 label cells, black borders, signature table, green note.
//  The backend ChecklistPdfService renders the identical layout, so
//  what the auditor previews here is what the client receives.
// ═══════════════════════════════════════════════════════════════

import React, { useRef } from "react";

export interface ChecklistPdfData {
  auditCode: string;
  companyName: string;
  auditLine: string;
  standardName: string;
  items: string[];
  dueDate?: string | null;
  leadAuditorName?: string | null;
}

const LOGO_URL = "https://crm.qrs.ae/qrslogo.jpg";

const DOC_CSS = `
  @page { size: A4; margin: 12mm; }
  * { box-sizing: border-box; }
  body { font-family: Arial, Helvetica, sans-serif; font-size: 11px; margin: 0; padding: 15px; color: #333; letter-spacing: .2px; }
  table { border-collapse: collapse; width: 100%; }
  td, th { border: 1px solid #000; padding: 8px; vertical-align: top; }
  .hdr .brand { text-align: center; vertical-align: middle; padding: 10px; }
  .hdr .brand img { height: 60px; vertical-align: middle; }
  .hdr .brand span { font-size: 20px; font-weight: bold; vertical-align: middle; margin-left: 10px; letter-spacing: 1px; display: inline-block; text-align: center; }
  .hdr .page { width: 13%; text-align: right; vertical-align: top; font-size: 10px; }
  .hdr .title { text-align: center; font-weight: bold; font-size: 15px; padding: 10px; }
  .hdr .form { text-align: right; vertical-align: bottom; font-size: 11px; }
  .main-table { margin: 15px 0; }
  .main-table th { background: #adcff6; text-align: left; width: 20%; font-size: 11px; }
  .main-table td { font-size: 12px; color: #0a0a0a; }
  .items th { background: #adcff6; font-size: 10px; }
  .items td { font-size: 11.5px; color: #0a0a0a; }
  .box { text-align: center; font-family: 'DejaVu Sans', Arial, sans-serif; font-size: 14px; }
  .sig th { background: none; text-align: left; width: 25%; font-size: 11px; }
  .sig td { width: 25%; font-size: 11.5px; color: #0a0a0a; }
  .footer-note { background: #d4edda; color: #155724; padding: 10px; border-radius: 5px; margin-top: 15px; border: 0; }
  .page-number { text-align: right; font-size: 10px; margin-top: 10px; }
`;

export function buildChecklistDocumentHtml(d: ChecklistPdfData): string {
  const esc = (s: string) =>
    String(s ?? "").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
  const rows = d.items
    .map(
      (text, i) =>
        `<tr><td style="width:5%">${i + 1}.</td><td>${esc(text)}</td><td class="box" style="width:12%">&#9633;</td><td style="width:18%"></td></tr>`,
    )
    .join("");
  return `<!DOCTYPE html><html><head><meta charset="UTF-8"><style>${DOC_CSS}</style></head><body>

<table class="hdr" style="margin-bottom:15px">
  <tr>
    <td class="brand" style="width:87%">
      <img src="${LOGO_URL}" alt="QRS" onerror="this.style.display='none'"/>
      <span>QUALITY REGISTRAR<br/>SYSTEMS</span>
    </td>
    <td class="page">Page 1 of 1</td>
  </tr>
  <tr>
    <td class="title">DOCUMENT REQUEST CHECKLIST</td>
    <td class="form">Form</td>
  </tr>
</table>

<table class="main-table">
  <tr><th>COMPANY</th><td><b>${esc(d.companyName)}</b></td></tr>
  <tr><th>AUDIT</th><td>${esc(d.auditLine || "—")}</td></tr>
  <tr><th>STANDARD</th><td>${esc(d.standardName)}</td></tr>
  <tr><th>DOCUMENTS</th><td>${d.items.length} requested${d.dueDate ? ` &nbsp;·&nbsp; Due: <b>${esc(d.dueDate)}</b>` : ""}</td></tr>
</table>

<table class="items">
  <thead><tr>
    <th style="width:5%;text-align:left">S#</th>
    <th style="text-align:left">DOCUMENT REQUIRED</th>
    <th style="width:12%">PROVIDED</th>
    <th style="width:18%">REMARKS</th>
  </tr></thead>
  <tbody>${rows}</tbody>
</table>

<table class="sig" style="margin-top:16px">
  <tr>
    <th>Auditor Signature:</th><td>${esc(d.leadAuditorName || "")}</td>
    <th>Auditee Signature:</th><td></td>
  </tr>
  <tr>
    <th>Date:</th><td></td>
    <th>Date:</th><td></td>
  </tr>
</table>

<p class="footer-note">
  Please upload each requested document on your <strong>QRS client portal</strong>${d.dueDate ? ` before <strong>${esc(d.dueDate)}</strong>` : ""}. This checklist PDF is attached to your notification email for reference.
</p>

<div class="page-number">Page 1 of 1</div>

</body></html>`;
}

export default function ChecklistPdfPreview({ data }: { data: ChecklistPdfData }) {
  const html = buildChecklistDocumentHtml(data);
  const printing = useRef(false);

  const handlePrint = () => {
    if (printing.current) return;
    printing.current = true;
    const iframe = document.createElement("iframe");
    iframe.style.position = "fixed";
    iframe.style.right = "0";
    iframe.style.bottom = "0";
    iframe.style.width = "0";
    iframe.style.height = "0";
    iframe.style.border = "0";
    document.body.appendChild(iframe);
    const doc = iframe.contentWindow?.document;
    if (doc) {
      doc.open();
      doc.write(html);
      doc.close();
      setTimeout(() => {
        iframe.contentWindow?.focus();
        iframe.contentWindow?.print();
      }, 350);
    }
    setTimeout(() => {
      document.body.removeChild(iframe);
      printing.current = false;
    }, 1800);
  };

  return (
    <div>
      <div
        style={{
          background: "#565160",
          borderRadius: 14,
          padding: "24px 0",
          display: "flex",
          justifyContent: "center",
        }}
      >
        <div
          style={{
            width: 680,
            maxWidth: "94%",
            background: "#fff",
            boxShadow: "0 22px 60px rgba(0,0,0,.4)",
          }}
        >
          <iframe
            title="Checklist PDF preview"
            srcDoc={html}
            style={{ width: "100%", height: 620, border: 0, display: "block" }}
          />
        </div>
      </div>
      <div style={{ display: "flex", gap: 8, marginTop: 12 }}>
        <button type="button" onClick={handlePrint} style={btnGray}>
          🖨 Print
        </button>
        <button type="button" onClick={handlePrint} style={btnGray}>
          ⬇ Save as PDF
        </button>
      </div>
    </div>
  );
}

const btnGray: React.CSSProperties = {
  display: "inline-flex",
  alignItems: "center",
  gap: 7,
  borderRadius: 10,
  fontWeight: 800,
  fontSize: 12.5,
  padding: "9px 15px",
  cursor: "pointer",
  background: "#f8fafc",
  color: "#475569",
  border: "1px solid #e2e8f0",
};