/* global React, Icon, Modal, QR, formatBaht, formatDateTH */
const { useState: useStateD2 } = React;

function InvoiceDoc({ room, copyLabel, headerLines, footerLines }) {
  const usedWater = (room.currMeter?.water || 0) - (room.prevMeter?.water || 0);
  const usedElec = (room.currMeter?.electric || 0) - (room.prevMeter?.electric || 0);
  const waterCost = usedWater * room.waterRate;
  const elecCost = usedElec * room.electricRate;
  const extras = room.extras || [];
  const extraSum = extras.reduce((s,x) => s + Number(x.amount || 0), 0);
  const total = room.rent + waterCost + elecCost + extraSum;
  const period = "พฤษภาคม 2569";
  const docNo = "INV-2026-05-" + room.no;
  const projName = window.__TWEAK_DEFAULTS?.brand || "ParkingHome";
  const hLines = headerLines || ["123 ซ.สุขสำราญ ถ.สามัคคี กรุงเทพฯ 10220 · โทร 02-123-4567", "เลขที่ผู้เสียภาษี 0-1234-56789-01-2"];
  const fLines = footerLines || ["ขอบคุณที่ใช้บริการ"];

  return (
    <div className="doc">
      {copyLabel && (
        <div className="copy-label" style={{ textAlign: "right", fontWeight: 700, fontSize: "0.85rem", letterSpacing: "0.08em", color: copyLabel === "ต้นฉบับ" ? "var(--accent)" : "#888", marginBottom: 4 }}>
          — {copyLabel} —
        </div>
      )}
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", borderBottom: "3px solid var(--accent)", paddingBottom: 14, marginBottom: 14 }}>
        <div>
          <div style={{ fontSize: "0.8rem", color: "#666", letterSpacing: "0.1em", textTransform: "uppercase" }}>ใบแจ้งหนี้ / INVOICE</div>
          <h2 style={{ marginTop: 4, color: "var(--accent)" }}>{projName}</h2>
          {hLines.map((l, i) => <div key={i} className="small">{l}</div>)}
        </div>
        <div style={{ textAlign: "right" }}>
          <div className="small"><b>เลขที่:</b> {docNo}</div>
          <div className="small"><b>วันที่:</b> {formatDateTH("2026-05-11")}</div>
          <div className="small"><b>กำหนดชำระ:</b> {formatDateTH("2026-05-20")}</div>
        </div>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16, marginBottom: 12 }}>
        <div>
          <div className="small" style={{ color: "#888" }}>เรียกเก็บจาก</div>
          <div style={{ fontWeight: 600, fontSize: "1.05rem" }}>{room.customer?.name || "—"}</div>
          <div className="small">โทรศัพท์ {room.customer?.phone}</div>
          <div className="small">รหัสลูกค้า {room.customer?.id}</div>
        </div>
        <div>
          <div className="small" style={{ color: "#888" }}>รายละเอียดห้องพัก</div>
          <div style={{ fontWeight: 600, fontSize: "1.05rem" }}>ห้อง {room.no} · ชั้น {room.floor}</div>
          <div className="small">{room.size}</div>
          <div className="small">รอบบิล {period}</div>
        </div>
      </div>

      <table>
        <colgroup>
          <col style={{ width: "38%" }}/>
          <col style={{ width: "13%" }}/>
          <col style={{ width: "13%" }}/>
          <col style={{ width: "10%" }}/>
          <col style={{ width: "26%" }}/>
        </colgroup>
        <thead>
          <tr>
            <th>รายการ</th>
            <th className="num">หน่วยก่อน</th>
            <th className="num">หน่วยนี้</th>
            <th className="num">ใช้</th>
            <th className="num">รวม</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td>ค่าเช่าห้องพัก</td>
            <td className="num" style={{ color: "#aaa" }}>—</td>
            <td className="num" style={{ color: "#aaa" }}>—</td>
            <td className="num" style={{ color: "#aaa" }}>—</td>
            <td className="num">{formatBaht(room.rent)}</td>
          </tr>
          <tr>
            <td>ค่าน้ำประปา</td>
            <td className="num">{room.prevMeter.water}</td>
            <td className="num">{room.currMeter.water}</td>
            <td className="num">{usedWater}</td>
            <td className="num">{formatBaht(waterCost)}</td>
          </tr>
          <tr>
            <td>ค่าไฟฟ้า</td>
            <td className="num">{room.prevMeter.electric}</td>
            <td className="num">{room.currMeter.electric}</td>
            <td className="num">{usedElec}</td>
            <td className="num">{formatBaht(elecCost)}</td>
          </tr>
          {extras.map((x, i) => (
            <tr key={i}>
              <td>{x.name}</td>
              <td className="num" style={{ color: "#aaa" }}>—</td>
              <td className="num" style={{ color: "#aaa" }}>—</td>
              <td className="num" style={{ color: "#aaa" }}>—</td>
              <td className="num">{formatBaht(x.amount)}</td>
            </tr>
          ))}
        </tbody>
      </table>

      <div className="total">
        <div>รวมทั้งสิ้น</div>
        <div>{formatBaht(total)}</div>
      </div>

      <div className="divider"/>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end", marginTop: 10 }}>
        <div>
          {fLines.map((l, i) => <div key={i} className="small" style={{ color: "#888" }}>{l}</div>)}
        </div>
        <div style={{ textAlign: "center", minWidth: 180 }}>
          <div style={{ borderBottom: "1px solid #333", marginBottom: 4, height: 28 }}/>
          <div className="small" style={{ fontWeight: 600 }}>ผู้บันทึก</div>
          <div className="small" style={{ color: "#aaa", marginTop: 2 }}>วันที่ ................................</div>
        </div>
      </div>
    </div>
  );
}

function ReceiptThermal({ data, headerLines, footerLines }) {
  const isDaily = data._isDailyPark;
  const date = data.date || "2026-05-11";
  const deposit = (!isDaily && data.no && data.floor !== undefined) ? (data.customer?.deposit || 0) : 0;

  const baseAmount = isDaily ? data.amount : (data.rent || data.monthly || 0);
  const total = baseAmount + deposit;

  return (
    <div className="doc thermal" id="print-doc">
      <div style={{ textAlign: "center" }}>
        {headerLines.map((line, i) =>
          i === 0
            ? <h2 key={i} style={{ fontSize: "1.1rem" }}>{line}</h2>
            : <div key={i} className="small">{line}</div>
        )}
      </div>
      <div className="divider"/>
      <div className="docrow"><span>เลขที่:</span><span className="num">RC-{date.replace(/-/g,"")}-{data.no || data.spot || "X"}</span></div>
      <div className="docrow"><span>วันที่:</span><span>{formatDateTH(date)}</span></div>
      <div className="divider"/>
      {isDaily ? (
        <>
          <div className="docrow"><span>ทะเบียนรถ</span><span className="mono">{data.plate}</span></div>
          <div className="docrow"><span>ช่องจอด</span><span>{data.spot}</span></div>
          <div className="docrow"><span>ระยะเวลา</span><span>{data.hours} ชม.</span></div>
          <div className="divider"/>
          <div className="docrow bold"><span>ค่าจอดรถ</span><span>{formatBaht(data.amount)}</span></div>
        </>
      ) : data.no && data.floor !== undefined ? (
        <>
          <div className="docrow"><span>ห้อง</span><span>{data.no}</span></div>
          <div className="docrow"><span>ผู้เช่า</span><span>{data.customer?.name || "—"}</span></div>
          {data.customer?.since && <div className="docrow"><span>วันที่เข้าพัก</span><span>{formatDateTH(data.customer.since)}</span></div>}
          {data.customer?.checkoutPlan && <div className="docrow"><span>กำหนดออก</span><span>{formatDateTH(data.customer.checkoutPlan)}</span></div>}
          <div className="divider"/>
          <div className="docrow"><span>ค่าห้องพัก × 1 คืน</span><span>{formatBaht(data.rent)}</span></div>
          {deposit > 0 && <div className="docrow"><span>ค่าประกัน/มัดจำ</span><span>{formatBaht(deposit)}</span></div>}
        </>
      ) : (
        <>
          <div className="docrow"><span>ช่องจอด</span><span>{data.no}</span></div>
          <div className="docrow"><span>ผู้เช่า</span><span>{data.customer?.name || "—"}</span></div>
          <div className="docrow"><span>ทะเบียน</span><span className="mono">{data.plate}</span></div>
          <div className="divider"/>
          <div className="docrow"><span>ค่าเช่ารายเดือน</span><span>{formatBaht(data.monthly)}</span></div>
        </>
      )}
      <div className="divider"/>
      <div className="docrow bold" style={{ fontSize: "1.05rem" }}>
        <span>รวมทั้งสิ้น</span>
        <span>{formatBaht(total)}</span>
      </div>
      <div className="docrow"><span>ชำระโดย</span><span>{data.method || "เงินสด"}</span></div>
      <div className="divider"/>
      {footerLines.map((line, i) => (
        <div key={i} className="small" style={{ textAlign: "center", color: i === 0 ? "#555" : "#888", marginTop: i === 0 ? 0 : 4 }}>{line}</div>
      ))}
    </div>
  );
}

function DocumentModal({ doc, onClose, thermalHeader, setThermalHeader, thermalFooter, setThermalFooter, invoiceHeaderLines, setInvoiceHeaderLines, invoiceFooterLines, setInvoiceFooterLines }) {
  if (!doc) return null;
  const isInvoice = doc.kind === "invoice";
  const [downloading, setDownloading] = useStateD2(false);
  const [showTextEdit, setShowTextEdit] = useStateD2(false);

  // select the right header/footer based on doc type
  const headerLines = isInvoice ? (invoiceHeaderLines || []) : (thermalHeader || []);
  const footerLines = isInvoice ? (invoiceFooterLines || []) : (thermalFooter || []);
  const setHeaderLines = isInvoice ? setInvoiceHeaderLines : setThermalHeader;
  const setFooterLines = isInvoice ? setInvoiceFooterLines : setThermalFooter;

  const updateHeader = (i, val) => setHeaderLines(ls => ls.map((l, j) => j === i ? val : l));
  const updateFooter = (i, val) => setFooterLines(ls => ls.map((l, j) => j === i ? val : l));
  const addHeaderLine = () => setHeaderLines(ls => [...ls, ""]);
  const removeHeaderLine = (i) => setHeaderLines(ls => ls.filter((_, j) => j !== i));
  const addFooterLine = () => setFooterLines(ls => [...ls, ""]);
  const removeFooterLine = (i) => setFooterLines(ls => ls.filter((_, j) => j !== i));

  const handleDownloadPDF = () => {
    const area = document.getElementById("print-area");
    if (!area || typeof html2pdf === "undefined") return;
    setDownloading(true);

    // Apply screen-equivalent of @media print styles so html2canvas can capture
    area.style.cssText = "display:flex;flex-direction:column;position:fixed;top:0;left:0;width:794px;height:1123px;overflow:hidden;background:white;z-index:99999;";
    const copies = area.querySelectorAll(".print-copy");
    copies.forEach(cp => {
      cp.style.cssText = "width:794px;height:549px;overflow:hidden;flex-shrink:0;box-sizing:border-box;padding:22px 30px 15px;";
      const d = cp.querySelector(".doc");
      if (d) d.style.cssText = "padding:0;max-width:none;background:white;box-shadow:none;zoom:0.72;";
      const lbl = cp.querySelector(".copy-label");
      if (lbl) lbl.style.display = "block";
    });
    const sep = area.querySelector(".print-copy-sep");
    if (sep) sep.style.cssText = "border-top:1.5px dashed #bbb;height:25px;flex-shrink:0;display:block;";

    const filename = "INV-2026-05-" + (doc.data?.no || "X") + ".pdf";
    html2pdf().set({
      margin: 0,
      filename,
      image: { type: "jpeg", quality: 0.98 },
      html2canvas: { scale: 2, useCORS: true, logging: false, windowWidth: 794 },
      jsPDF: { unit: "px", format: [794, 1123], orientation: "portrait" }
    }).from(area).save().then(() => {
      area.style.cssText = "";
      copies.forEach(cp => {
        cp.style.cssText = "";
        const d = cp.querySelector(".doc");
        if (d) d.style.cssText = "";
        const lbl = cp.querySelector(".copy-label");
        if (lbl) lbl.style.display = "";
      });
      if (sep) sep.style.cssText = "";
      setDownloading(false);
    });
  };

  return (
    <Modal open={!!doc} onClose={onClose} size="xl"
      title={isInvoice ? "ใบแจ้งหนี้" : "ใบเสร็จรับเงิน"}
      footer={
        <>
          <button className="btn" onClick={onClose}>ปิด</button>
          <button className="btn" onClick={() => setShowTextEdit(v => !v)}>
            <Icon name="edit" size={16}/> {showTextEdit ? "ซ่อนแก้ไข" : "แก้ไขข้อความ"}
          </button>
          <button className="btn" onClick={() => window.print()}><Icon name="printer" size={16}/> พิมพ์</button>
          <button className="btn primary" onClick={handleDownloadPDF} disabled={downloading}>
            <Icon name="download" size={16}/> {downloading ? "กำลังสร้าง PDF..." : "ดาวน์โหลด PDF"}
          </button>
        </>
      }>
      <div style={{ background: "var(--bg)", padding: 20, borderRadius: 12 }}>
        {isInvoice
          ? <InvoiceDoc room={doc.data} headerLines={invoiceHeaderLines} footerLines={invoiceFooterLines}/>
          : <ReceiptThermal data={doc.data} headerLines={headerLines} footerLines={footerLines}/>}
      </div>

      {showTextEdit && (
        <div style={{ marginTop: 16, padding: 16, background: "var(--surface-2)", borderRadius: 12, display: "grid", gap: 14 }}>
          <div>
            <div style={{ fontWeight: 600, marginBottom: 8, fontSize: "0.9rem" }}>ส่วนหัว</div>
            {headerLines.map((line, i) => (
              <div key={i} className="row" style={{ gap: 8, marginBottom: 6 }}>
                <input className="input" style={{ flex: 1 }} value={line} onChange={e => updateHeader(i, e.target.value)}
                  placeholder={i === 0 ? "ชื่อกิจการ" : "บรรทัดเพิ่มเติม"}/>
                {headerLines.length > 1 && (
                  <button className="btn sm danger" onClick={() => removeHeaderLine(i)}><Icon name="trash" size={13}/></button>
                )}
              </div>
            ))}
            <button className="btn sm" onClick={addHeaderLine}><Icon name="plus" size={13}/> เพิ่มบรรทัด</button>
          </div>
          <div style={{ borderTop: "1px solid var(--line)", paddingTop: 14 }}>
            <div style={{ fontWeight: 600, marginBottom: 8, fontSize: "0.9rem" }}>ส่วนท้าย</div>
            {footerLines.map((line, i) => (
              <div key={i} className="row" style={{ gap: 8, marginBottom: 6 }}>
                <input className="input" style={{ flex: 1 }} value={line} onChange={e => updateFooter(i, e.target.value)}
                  placeholder="ข้อความท้ายใบเสร็จ"/>
                {footerLines.length > 1 && (
                  <button className="btn sm danger" onClick={() => removeFooterLine(i)}><Icon name="trash" size={13}/></button>
                )}
              </div>
            ))}
            <button className="btn sm" onClick={addFooterLine}><Icon name="plus" size={13}/> เพิ่มบรรทัด</button>
          </div>
        </div>
      )}

      {isInvoice ? (
        <div id="print-area">
          <div className="print-copy">
            <InvoiceDoc room={doc.data} copyLabel="ต้นฉบับ" headerLines={invoiceHeaderLines} footerLines={invoiceFooterLines}/>
          </div>
          <div className="print-copy-sep"/>
          <div className="print-copy">
            <InvoiceDoc room={doc.data} copyLabel="สำเนา" headerLines={invoiceHeaderLines} footerLines={invoiceFooterLines}/>
          </div>
        </div>
      ) : (
        <div id="print-area" className="thermal-print">
          <ReceiptThermal data={doc.data} headerLines={headerLines} footerLines={footerLines}/>
        </div>
      )}
    </Modal>
  );
}

window.DocumentModal = DocumentModal;
