// ==============================================
// Thai-style formal Quotation PDF preview + download
// ==============================================

function QuotationPreview({ quote, navigate, onNewQuote, apiStatus }) {
  const docRef = useRef(null);
  const toast = useToast();
  const [downloading, setDownloading] = useState(false);
  const [sent, setSent] = useState(false);
  const [sentDialog, setSentDialog] = useState(false);

  const download = async () => {
    if (!docRef.current || downloading) return;
    setDownloading(true);
    try {
      const opt = {
        margin: 0,
        filename: `Quotation-${quote.no}.pdf`,
        image: { type: "jpeg", quality: 0.96 },
        html2canvas: { scale: 2, useCORS: true, backgroundColor: "#ffffff" },
        jsPDF: { unit: "pt", format: "a4", orientation: "portrait" },
      };
      await window.html2pdf().set(opt).from(docRef.current).save();
      toast("ดาวน์โหลด PDF เรียบร้อย");
    } catch (e) {
      console.error(e);
      toast("เกิดข้อผิดพลาดในการสร้าง PDF", "err");
    } finally {
      setDownloading(false);
    }
  };

  const print = () => {
    const printWindow = window.open("", "_blank");
    if (!printWindow || !docRef.current) return;
    const styles = Array.from(document.styleSheets)
      .map(ss => {
        try {
          return Array.from(ss.cssRules).map(r => r.cssText).join("\n");
        } catch { return ""; }
      }).join("\n");
    printWindow.document.write(`
      <!DOCTYPE html><html><head><title>Quotation ${quote.no}</title>
      <link rel="preconnect" href="https://fonts.googleapis.com">
      <link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Sans+Thai:wght@400;500;600;700&family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet">
      <style>${styles} body{background:white;margin:0;padding:0} .pdf-doc{box-shadow:none;width:auto;margin:0;padding: 40px 50px;}</style></head>
      <body>${docRef.current.outerHTML}<script>setTimeout(()=>{window.print();},800);<\/script></body></html>
    `);
    printWindow.document.close();
  };

  const sendEmail = () => {
    setSent(true);
    setSentDialog(true);
    setTimeout(() => setSent(false), 1500);
  };

  return (
    <div>
      <div className="card mb-16">
        <div className="pdf-controls">
          <span className="bold">{quote.no}</span>
          <span className="muted small">· {quote.date}</span>
          {quote.savedToDb
            ? <span className="chip ok"><Icon name="check" size={12}/> บันทึกลง Database แล้ว</span>
            : <span className="chip ok"><Icon name="check" size={12}/> สร้างสำเร็จ</span>
          }
          <div style={{ flex: 1 }}></div>
          <button className="btn btn-outline" onClick={print}>
            <Icon name="print" size={14}/> พิมพ์
          </button>
          <button className={"btn " + (sent ? "btn-outline" : "btn-outline")} onClick={sendEmail}>
            <Icon name={sent ? "check" : "send"} size={14}/> {sent ? "ส่งแล้ว" : "ส่งอีเมล"}
          </button>
          <button className="btn btn-primary" onClick={download} disabled={downloading}>
            <Icon name="download" size={14}/> {downloading ? "กำลังสร้าง PDF..." : "ดาวน์โหลด PDF"}
          </button>
        </div>

        <div className="pdf-shell">
          <PdfDocument quote={quote} docRef={docRef}/>
        </div>
      </div>

      <div className="flex gap-8 between">
        <button className="btn btn-ghost" onClick={() => navigate("cart")}>
          <Icon name="chevron-right" size={14} style={{transform:"rotate(180deg)"}}/> กลับไปแก้ไขรายการสินค้า
        </button>
        <button className="btn btn-primary" onClick={onNewQuote}>
          <Icon name="plus" size={14}/> สร้างใบเสนอราคาใหม่
        </button>
      </div>

      <Modal open={sentDialog} onClose={() => setSentDialog(false)} title="ส่งอีเมลเรียบร้อย" footer={
        <button className="btn btn-primary" onClick={() => setSentDialog(false)}>เข้าใจแล้ว</button>
      }>
        <div className="flex gap-16 center">
          <div style={{ width: 56, height: 56, borderRadius: 28, background: "var(--green-bg)", color: "var(--green)", display: "grid", placeItems: "center" }}>
            <Icon name="check" size={28}/>
          </div>
          <div>
            <div className="bold mb-8">ระบบได้ส่งใบเสนอราคาไปยังอีเมลของลูกค้าแล้ว</div>
            <div className="muted small">{quote.customer.email}</div>
            <div className="muted small mt-8">หากไม่ได้รับอีเมล กรุณาตรวจสอบที่กล่อง Spam หรือดาวน์โหลด PDF ด้านบน</div>
          </div>
        </div>
      </Modal>
    </div>
  );
}

/* ----- The actual PDF document (rendered for screen + html2pdf) ----- */
function PdfDocument({ quote, docRef }) {
  const { customer, items, isDealer, subtotal, dealerDiscount, vat, total, no, date } = quote;

  return (
    <div className="pdf-doc" ref={docRef}>
      <div className="pdf-header">
        <div className="pdf-logo-wrap">
          <div className="pdf-logo"><img src="assets/logo.png" alt="Inter Supply"/></div>
          <div className="pdf-co">
            <div className="name-th">บริษัท อินเตอร์ ซัพพลาย (1992) จำกัด</div>
            <div className="name-en">INTER SUPPLY (1992) CO., LTD.</div>
            <div className="addr">
              123/45 หมู่ 7 ถ.บางนา-ตราด กม.20<br/>
              ต.บางพลีใหญ่ อ.บางพลี จ.สมุทรปราการ 10540<br/>
              โทร. 02-555-1992 · sales@intersupply.co.th<br/>
              เลขประจำตัวผู้เสียภาษี: 0105535012345
            </div>
          </div>
        </div>
        <div className="pdf-title">
          <h1>ใบเสนอราคา</h1>
          <div className="en">QUOTATION</div>
          <div style={{marginTop: 14, textAlign:"right", fontSize: 10.5, lineHeight: 1.6}}>
            <div><span style={{color:"var(--ink-500)"}}>เลขที่ / No.</span> <b className="mono">{no}</b></div>
            <div><span style={{color:"var(--ink-500)"}}>วันที่ / Date</span> <b>{date}</b></div>
            <div><span style={{color:"var(--ink-500)"}}>ยืนยันราคา / Valid</span> <b>30 วัน · 30 days</b></div>
            <div><span style={{color:"var(--ink-500)"}}>พนักงานขาย / By</span> <b>คุณวารีพร (ฝ่ายขาย)</b></div>
          </div>
        </div>
      </div>

      <div className="pdf-meta">
        <div className="box">
          <div className="lbl">Bill To / ลูกค้า</div>
          <div className="name">{customer.company || customer.name}</div>
          {customer.company && <div className="row">ผู้ติดต่อ: {customer.name}</div>}
          <div className="row" style={{whiteSpace:"pre-wrap"}}>{customer.address}</div>
          {customer.taxId && <div className="row">เลขผู้เสียภาษี: {customer.taxId}</div>}
          <div className="row">โทร. {customer.phone} · {customer.email}</div>
        </div>
        <div className="box">
          <div className="lbl">Reference / อ้างอิง</div>
          <dl className="info-row" style={{margin:0}}>
            <dt>โครงการ</dt><dd>{customer.project || "—"}</dd>
            <dt>เงื่อนไขการชำระเงิน</dt><dd>เงินสด / โอน {isDealer ? "(Credit 30 วัน)" : ""}</dd>
            <dt>การจัดส่ง</dt><dd>1-3 วันทำการ</dd>
            <dt>สถานที่จัดส่ง</dt><dd>ตามที่อยู่ลูกค้า</dd>
          </dl>
        </div>
      </div>

      <table className="pdf-table">
        <thead>
          <tr>
            <th style={{width: 28}} className="center">#</th>
            <th style={{width: 52}} className="center">รูป</th>
            <th>รายการสินค้า / Description</th>
            <th className="center" style={{width: 50}}>จำนวน</th>
            <th className="center" style={{width: 44}}>หน่วย</th>
            <th className="right" style={{width: 76}}>ราคา/หน่วย</th>
            {isDealer && <th className="right" style={{width: 50}}>ส่วนลด</th>}
            <th className="right" style={{width: 84}}>จำนวนเงิน</th>
          </tr>
        </thead>
        <tbody>
          {items.map((it, i) => {
            const unitOrig = it.price;
            const unit = isDealer ? it.dealerPrice : it.price;
            const lineTotal = unit * it.qty;
            return (
              <React.Fragment key={it.id}>
                <tr>
                  <td className="center">{i + 1}</td>
                  <td className="pdf-img-cell center">
                    <div className="pdf-thumb">
                      {window.ProductPhoto && <window.ProductPhoto product={it} simple={true} />}
                    </div>
                  </td>
                  <td>
                    <div style={{ fontWeight: 600, fontSize: 11.5 }}>{it.th}</div>
                    <div className="sku">{it.sku} · {it.brand}{it.en ? ` · ${it.en}` : ""}</div>
                  </td>
                  <td className="center">{it.qty}</td>
                  <td className="center">ชิ้น</td>
                  <td className="right">
                    {isDealer && unit !== unitOrig && <div style={{textDecoration:"line-through", color:"var(--ink-400)", fontSize:10}}>{fmtMoney(unitOrig)}</div>}
                    {fmtMoney(unit)}
                  </td>
                  {isDealer && <td className="right" style={{color:"var(--amber)"}}>-15%</td>}
                  <td className="right" style={{fontWeight: 600}}>{fmtMoney(lineTotal)}</td>
                </tr>
                {it.note &&
                <tr className="note">
                    <td></td>
                    <td></td>
                    <td colSpan={isDealer ? 5 : 4}>
                      <span style={{color:"var(--navy-700)", fontWeight:600, fontStyle:"normal"}}>หมายเหตุ:</span> {it.note}
                    </td>
                  </tr>
                }
              </React.Fragment>
            );
          })}
          {/* filler row so table doesn't look short */}
          {items.length < 5 && Array.from({ length: 5 - items.length }).map((_, i) => (
            <tr key={`f-${i}`} style={{ height: 24 }}>
              <td style={{ color: "var(--ink-300)" }} className="center">{items.length + i + 1}</td>
              <td colSpan={isDealer ? 7 : 6}></td>
            </tr>
          ))}
        </tbody>
      </table>

      <div className="pdf-bottom">
        <div className="pdf-terms">
          <h4>เงื่อนไข / Terms & Conditions</h4>
          <ol>
            <li>ราคาที่เสนอเป็นบาทไทย รวม VAT 7% แล้ว</li>
            <li>ใบเสนอราคามีผลภายใน 30 วันนับจากวันที่ออก</li>
            <li>ระยะเวลาจัดส่ง 1-3 วันทำการ หลังจากได้รับการยืนยันคำสั่งซื้อ</li>
            <li>เงื่อนไขการชำระเงิน: ชำระเต็มจำนวนก่อนจัดส่ง / โอนผ่านธนาคาร{isDealer ? " (Dealer Credit 30 วัน)" : ""}</li>
            <li>โอนเข้าบัญชี: ธ.กรุงเทพ สาขาบางนา 123-4-56789-0 ชื่อบัญชี บจก. อินเตอร์ ซัพพลาย (1992)</li>
            <li>รับประกันสินค้าตามเงื่อนไขผู้ผลิต โปรดเก็บใบกำกับภาษีไว้เป็นหลักฐาน</li>
            <li>กรณีสั่งซื้อกรุณายืนยันโดยลงนามและส่งกลับมาที่ sales@intersupply.co.th</li>
          </ol>
          {customer.note && (
            <div style={{marginTop: 8, paddingTop: 6, borderTop: "1px dashed var(--ink-200)"}}>
              <h4>หมายเหตุจากลูกค้า</h4>
              <div style={{fontSize: 10.5, color: "var(--ink-700)"}}>{customer.note}</div>
            </div>
          )}
        </div>
        <div>
          <div className="pdf-totals-box">
            <div className="row">
              <span className="l">รวมเป็นเงิน / Subtotal</span>
              <span>{fmtMoney(subtotal + (isDealer ? dealerDiscount : 0))}</span>
            </div>
            {isDealer && (
              <div className="row" style={{color:"var(--amber)"}}>
                <span className="l">ส่วนลด Dealer 15%</span>
                <span>- {fmtMoney(dealerDiscount)}</span>
              </div>
            )}
            <div className="row">
              <span className="l">ราคาก่อน VAT</span>
              <span>{fmtMoney(subtotal)}</span>
            </div>
            <div className="row">
              <span className="l">ภาษีมูลค่าเพิ่ม 7%</span>
              <span>{fmtMoney(vat)}</span>
            </div>
            <div className="row total">
              <span className="l">รวมทั้งสิ้น (THB)</span>
              <span>{fmtMoney(total)}</span>
            </div>
          </div>
          <div className="small muted mt-8" style={{fontSize: 9.5, lineHeight: 1.4}}>
            จำนวนเงินตัวอักษร: <b style={{color:"var(--ink-900)"}}>{bahtText(total)}</b>
          </div>
        </div>
      </div>

      <div className="pdf-signatures">
        <div className="pdf-sig">
          <div className="sig-line">
            <span style={{ color:"var(--ink-300)", fontFamily: "var(--font-mono)", fontSize: 10}}>(ลายเซ็นลูกค้า)</span>
          </div>
          <div style={{marginTop: 4, borderTop:"1px solid var(--ink-300)", paddingTop: 6}}>
            <div className="name">{customer.name}</div>
            <div className="role">ผู้สั่งซื้อ / Authorized Buyer</div>
            <div className="role" style={{marginTop: 4}}>วันที่ ............/............/............</div>
          </div>
        </div>
        <div className="pdf-sig">
          <div className="sig-line" style={{position:"relative"}}>
            <span style={{ fontFamily: "var(--font-mono)", fontSize: 18, color: "var(--navy-800)", transform:"rotate(-8deg) translateY(-4px)", display:"inline-block", fontStyle:"italic", fontWeight: 600 }}>
              วารีพร / W.Pakdee
            </span>
            <span className="stamp" style={{position:"absolute", right: -8, top: 6}}>
              INTER SUPPLY<br/>1992<br/>VERIFIED
            </span>
          </div>
          <div style={{marginTop: 4, borderTop:"1px solid var(--ink-300)", paddingTop: 6}}>
            <div className="name">คุณวารีพร ภักดี · ผู้มีอำนาจลงนาม</div>
            <div className="role">ผู้จัดการฝ่ายขาย · Inter Supply (1992) Co., Ltd.</div>
            <div className="role" style={{marginTop: 4}}>วันที่ {date}</div>
          </div>
        </div>
      </div>

      <div className="pdf-footer-bar">
        <span>Inter Supply (1992) Co., Ltd. · TAX ID 0105535012345</span>
        <span>www.intersupply1992.co.th · {no} · Page 1/1</span>
      </div>
    </div>
  );
}

/* Convert number to Thai Baht text (simple) */
function bahtText(num) {
  const numbers = ["ศูนย์", "หนึ่ง", "สอง", "สาม", "สี่", "ห้า", "หก", "เจ็ด", "แปด", "เก้า"];
  const places = ["", "สิบ", "ร้อย", "พัน", "หมื่น", "แสน", "ล้าน"];
  function readInt(n) {
    n = Math.floor(n);
    if (n === 0) return "ศูนย์";
    let s = "";
    const str = n.toString();
    const len = str.length;
    for (let i = 0; i < len; i++) {
      const d = parseInt(str[i]);
      const place = len - i - 1;
      if (d === 0) continue;
      let num = numbers[d];
      if (place === 1 && d === 1) num = "";
      if (place === 1 && d === 2) num = "ยี่";
      if (place === 0 && d === 1 && len > 1) num = "เอ็ด";
      s += num + (places[place] || "");
    }
    return s;
  }
  const baht = Math.floor(num);
  const sat = Math.round((num - baht) * 100);
  let txt = readInt(baht) + "บาท";
  txt += sat === 0 ? "ถ้วน" : readInt(sat) + "สตางค์";
  return txt;
}

Object.assign(window, { QuotationPreview, PdfDocument, bahtText });
