/* global React, I, UI, SSSData */
const { useState: useStateRV, useMemo: useMemoRV, useEffect: useEffectRV } = React;
const rvUI = window.UI;

// =============== Printable paper: ใบสำคัญรับเงิน ===============
// Evidence that a PERSON received money from the company (used when the payee
// cannot issue an official receipt / tax invoice). Payee acknowledges + signs.
function RVPaper({ rv }) {
  const C = window.SSSData.Company;
  const { fmtM, bahtText } = window.UI;
  const color = window.getDocColor("receipt-voucher");
  const colorSoft = window.hexA(color, 0.07);
  const colorLine = window.hexA(color, 0.22);

  const lines = rv.lines || [{ desc: rv.purpose, amount: rv.amount }];
  const subtotal = lines.reduce((s, l) => s + (Number(l.amount) || 0), 0);
  const wht = Number(rv.wht) || 0;
  const net = subtotal - wht;

  return (
    <div className="doc-paper print-target" style={{fontSize: 11.5, padding: 0, position: "relative", overflow: "hidden"}}>
      <div style={{height: 6, background: color}}/>
      <div style={{padding: "26px 36px 30px"}}>
        {/* Header */}
        <div style={{display: "grid", gridTemplateColumns: "1fr auto", gap: 24, marginBottom: 22, alignItems: "flex-start"}}>
          <div style={{display: "flex", gap: 20, alignItems: "flex-start"}}>
            <div style={{background: color, borderRadius: 6, alignSelf: "stretch", minHeight: 56, maxHeight: 80, display: "flex", alignItems: "center", justifyContent: "center", padding: "8px 16px", flexShrink: 0}}><img src="assets/logo-ink.png" alt={C.name} style={{width: 132, maxHeight: "100%", objectFit: "contain", display: "block"}}/></div>
            <div style={{paddingTop: 2}}>
              <div style={{fontWeight: 700, fontSize: 13.5, lineHeight: 1.25, color: "#0c0a09"}}>{C.name}</div>
              <div style={{fontSize: 10.5, color: "#78716c", marginTop: 1}}>{C.nameEn}</div>
              <div style={{fontSize: 10.5, color: "#57534e", marginTop: 6, lineHeight: 1.5, maxWidth: 360}}>{C.address}</div>
              <div style={{fontSize: 10.5, color: "#57534e", marginTop: 3}}>โทร {C.phone} · เลขประจำตัวผู้เสียภาษี <b style={{color: "#0c0a09"}}>{C.taxId}</b></div>
            </div>
          </div>
          <div style={{textAlign: "right", minWidth: 210}}>
            <h1 style={{margin: 0, fontSize: 26, fontWeight: 700, color, letterSpacing: "-0.02em", lineHeight: 1}}>ใบสำคัญรับเงิน</h1>
            <div style={{fontSize: 9.5, color: "#a8a29e", letterSpacing: "0.12em", marginTop: 4, fontWeight: 500}}>RECEIPT VOUCHER</div>
            <div style={{marginTop: 14, display: "inline-block", textAlign: "left", background: colorSoft, padding: "10px 14px", borderRadius: 4, minWidth: 190}}>
              <div style={{display: "flex", justifyContent: "space-between", gap: 14, fontSize: 11}}><span style={{color: "#78716c"}}>เลขที่</span><b className="mono" style={{color: "#0c0a09"}}>{rv.no}</b></div>
              <div style={{display: "flex", justifyContent: "space-between", gap: 14, fontSize: 11, marginTop: 3}}><span style={{color: "#78716c"}}>วันที่</span><b style={{color: "#0c0a09"}}>{rv.date}</b></div>
              {rv.ref && rv.ref !== "—" && <div style={{display: "flex", justifyContent: "space-between", gap: 14, fontSize: 11, marginTop: 3}}><span style={{color: "#78716c"}}>อ้างอิง</span><b className="mono" style={{color: "#0c0a09", fontSize: 10.5}}>{rv.ref}</b></div>}
            </div>
          </div>
        </div>

        {/* Payee acknowledgement */}
        <div style={{border: `1px solid ${colorLine}`, borderRadius: 6, overflow: "hidden", marginBottom: 16}}>
          <div style={{background: color, color: "white", padding: "6px 14px", fontSize: 10.5, fontWeight: 600, letterSpacing: "0.06em"}}>ผู้รับเงิน (PAYEE)</div>
          <div style={{padding: "12px 14px"}}>
            <div style={{fontSize: 12, color: "#44403c", lineHeight: 1.7}}>
              ข้าพเจ้า <b style={{color: "#0c0a09", fontSize: 13}}>{rv.payee}</b>
              {rv.idcard && <> &nbsp;เลขบัตรประจำตัวประชาชน <span className="mono" style={{color: "#0c0a09"}}>{rv.idcard}</span></>}
            </div>
            {rv.address && <div style={{fontSize: 11, color: "#57534e", marginTop: 3}}>ที่อยู่ {rv.address}</div>}
            <div style={{fontSize: 12, color: "#44403c", marginTop: 8, lineHeight: 1.6}}>
              ได้รับเงินจาก <b style={{color: "#0c0a09"}}>{C.name}</b> ตามรายการด้านล่างนี้ไว้เป็นการถูกต้องเรียบร้อยแล้ว
            </div>
          </div>
        </div>

        {/* Line items */}
        <table style={{borderCollapse: "separate", borderSpacing: 0, width: "100%"}}>
          <thead>
            <tr>
              <th style={{width: 30, background: color, color: "white", padding: "9px 6px", fontSize: 10.5, fontWeight: 600, textAlign: "center", borderTopLeftRadius: 4}}>#</th>
              <th style={{background: color, color: "white", padding: "9px 12px", fontSize: 10.5, fontWeight: 600, textAlign: "left"}}>รายการ</th>
              <th style={{width: 130, background: color, color: "white", padding: "9px 12px", fontSize: 10.5, fontWeight: 600, textAlign: "right", borderTopRightRadius: 4}}>จำนวนเงิน</th>
            </tr>
          </thead>
          <tbody>
            {lines.map((l, i) => (
              <tr key={i} style={{background: i % 2 === 0 ? "white" : "#fafaf9"}}>
                <td style={{padding: "11px 6px", borderBottom: "1px solid #f1efeb", textAlign: "center", fontSize: 11, color: "#78716c"}}>{i + 1}</td>
                <td style={{padding: "11px 12px", borderBottom: "1px solid #f1efeb", fontSize: 11.5, color: "#0c0a09"}}>{l.desc || "—"}</td>
                <td style={{padding: "11px 12px", borderBottom: "1px solid #f1efeb", textAlign: "right", fontSize: 11.5, fontWeight: 600, color: "#0c0a09"}}>{fmtM(Number(l.amount) || 0)}</td>
              </tr>
            ))}
            {[...Array(Math.max(0, 3 - lines.length))].map((_, i) => (
              <tr key={"e" + i}><td style={{padding: "11px 6px", borderBottom: "1px solid #f5f4f1"}}>&nbsp;</td><td style={{borderBottom: "1px solid #f5f4f1"}}></td><td style={{borderBottom: "1px solid #f5f4f1"}}></td></tr>
            ))}
          </tbody>
        </table>

        {/* Totals + payment method */}
        <div style={{display: "grid", gridTemplateColumns: "1.1fr 1fr", gap: 24, marginTop: 16}}>
          <div style={{fontSize: 11, color: "#57534e", lineHeight: 1.7}}>
            <div style={{textTransform: "uppercase", fontSize: 9.5, fontWeight: 700, color: "#44403c", letterSpacing: "0.08em", marginBottom: 6, paddingBottom: 4, borderBottom: `2px solid ${color}`, display: "inline-block"}}>วิธีการจ่ายเงิน</div>
            <div style={{marginTop: 6}}>จ่ายโดย: <b style={{color: "#0c0a09"}}>{rv.method}</b></div>
            {wht > 0 && <div>หัก ณ ที่จ่าย: <b style={{color: "#0c0a09"}}>{fmtM(wht)} บาท</b> (นำส่งสรรพากร)</div>}
            <div style={{marginTop: 10, padding: "8px 12px", background: "#fefdf9", border: "1px solid #f1efeb", borderRadius: 4, fontSize: 10.5, color: "#57534e"}}>
              <b style={{color: "#0c0a09"}}>หมายเหตุ:</b> แนบสำเนาบัตรประชาชนผู้รับเงิน (รับรองสำเนาถูกต้อง) เป็นหลักฐานประกอบ
            </div>
          </div>
          <div>
            <div style={{padding: "10px 14px", background: "#f7f6f4", borderRadius: "5px 5px 0 0", border: "1px solid #e7e5e4"}}>
              <div style={{display: "flex", justifyContent: "space-between", padding: "3px 0", fontSize: 11.5, color: "#57534e"}}><span>รวมเป็นเงิน</span><span style={{color: "#0c0a09"}}>{fmtM(subtotal)}</span></div>
              {wht > 0 && <div style={{display: "flex", justifyContent: "space-between", padding: "3px 0", fontSize: 11.5, color: "#57534e"}}><span>หัก ณ ที่จ่าย</span><span style={{color: "#0c0a09"}}>−{fmtM(wht)}</span></div>}
            </div>
            <div style={{display: "flex", justifyContent: "space-between", alignItems: "center", padding: "14px", background: color, color: "white", borderRadius: "0 0 5px 5px"}}>
              <span style={{fontSize: 12.5, fontWeight: 500}}>จำนวนเงินที่จ่ายจริง</span>
              <span style={{fontSize: 17, fontWeight: 700, fontVariantNumeric: "tabular-nums"}}>฿ {fmtM(net)}</span>
            </div>
            <div style={{padding: "6px 14px", fontSize: 10.5, color: "#57534e", fontStyle: "italic", textAlign: "right"}}>({bahtText(net)})</div>
          </div>
        </div>

        {/* Signatures */}
        <div style={{display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 30, marginTop: 40, fontSize: 10.5}}>
          {[
            { role: "ผู้รับเงิน", name: rv.payee },
            { role: "ผู้จ่ายเงิน", name: rv.payer || C.currentUser.name },
            { role: "ผู้อนุมัติ", name: C.currentUser.name }
          ].map((s, i) => (
            <div key={i} style={{textAlign: "center"}}>
              <div style={{borderTop: "1px dashed #57534e", paddingTop: 6, marginTop: 38}}>
                <div style={{fontWeight: 600, color: "#0c0a09"}}>{s.role}</div>
                <div style={{color: "#78716c", fontSize: 9.5, marginTop: 2}}>( {s.name} )</div>
                <div style={{color: "#a8a29e", fontSize: 9.5, marginTop: 2}}>วันที่ ____________</div>
              </div>
            </div>
          ))}
        </div>

        <div style={{marginTop: 26, paddingTop: 10, borderTop: `2px solid ${color}`, fontSize: 9.5, color: "#78716c", display: "flex", justifyContent: "space-between", alignItems: "center"}}>
          <span><b style={{color: "#44403c"}}>{C.name}</b> · {C.website}</span>
          <span>{rv.no} · ออกโดยระบบ SSS</span>
        </div>
      </div>
    </div>
  );
}

// =============== List page ===============
function ReceiptVouchers({ navigate }) {
  const D = window.SSSData;
  const { fmt0 } = window.UI;
  const rows = D.ReceiptVouchers;
  const total = rows.reduce((s, r) => s + r.amount, 0);
  const whtTotal = rows.reduce((s, r) => s + (r.wht || 0), 0);
  return (
    <window.DocListPage
      title="ใบสำคัญรับเงิน · Receipt Vouchers"
      sub="หลักฐานการจ่ายเงินให้บุคคลที่ออกใบเสร็จไม่ได้ — ผู้รับเงินเซ็นรับ + แนบสำเนาบัตร"
      docType="receipt-voucher" rows={rows}
      statusFilter={["จ่ายแล้ว", "ร่าง"]}
      createLabel="ออกใบสำคัญรับเงิน"
      onCreate={() => window.openReceiptVoucher && window.openReceiptVoucher()}
      onRowClick={(r) => navigate("receipt-vouchers/" + r.no)}
      kpis={[
        { label: "ใบสำคัญรับเงินเดือนนี้", value: rows.length, sub: `รวม ฿${fmt0(total)}`, icon: I.receipt },
        { label: "จ่ายเป็นเงินสด", value: rows.filter(r => r.method === "เงินสด").length, sub: `฿${fmt0(rows.filter(r=>r.method==='เงินสด').reduce((s,r)=>s+r.amount,0))}`, icon: I.money },
        { label: "หัก ณ ที่จ่าย", value: `฿${fmt0(whtTotal)}`, sub: "นำส่ง ภ.ง.ด.3", icon: I.calc },
        { label: "ผู้รับเงิน (บุคคล)", value: rows.length, sub: "ไม่มีใบเสร็จ/ใบกำกับ", icon: I.user }
      ]}
      columns={[
        { key: "no", label: "เลขที่", render: r => <span className="mono">{r.no}</span> },
        { key: "date", label: "วันที่" },
        { key: "payee", label: "ผู้รับเงิน", render: r => <span style={{fontWeight: 500}}>{r.payee}</span> },
        { key: "purpose", label: "รายการ", render: r => <span className="muted" style={{display: "block", maxWidth: 320, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap"}}>{r.purpose}</span> },
        { key: "method", label: "วิธีจ่าย" },
        { key: "amount", label: "จำนวนเงิน", right: true, render: r => <span className="amount">฿{fmt0(r.amount)}</span> },
        { key: "status", label: "สถานะ", render: r => <window.UI.Badge>{r.status}</window.UI.Badge> }
      ]}
    />
  );
}

// =============== Detail page ===============
function ReceiptVoucherDetail({ docId, navigate }) {
  const D = window.SSSData;
  const { Btn, Badge, Card, PageHead, Workflow, fmt0 } = window.UI;
  const rv = D.ReceiptVouchers.find(r => r.no === docId) || D.ReceiptVouchers[0];

  return (
    <>
      <PageHead
        title={<span style={{display: "flex", alignItems: "center", gap: 12}}>
          <Btn kind="ghost" size="sm" onClick={() => navigate("receipt-vouchers")}><I.chevronLeft size={14} className="icon"/>กลับ</Btn>
          ใบสำคัญรับเงิน <span className="mono" style={{fontSize: 16, color: "var(--ink-3)", fontWeight: 500}}>{rv.no}</span>
        </span>}
        sub={`ผู้รับเงิน: ${rv.payee} · ${rv.date}`}
        right={<>
          {rv.wht > 0 && <Btn icon={I.tax} kind="ghost" onClick={() => window.openWHTCertFromRV && window.openWHTCertFromRV(rv)}>ออก 50 ทวิ</Btn>}
          <Btn icon={I.print} kind="ghost" onClick={() => window.printDocPaperWithOptions()}>พิมพ์</Btn>
          <Btn icon={I.download} kind="primary" onClick={() => window.printDocPaperWithOptions()}>ดาวน์โหลด PDF</Btn>
        </>}
      />
      <div className="grid" style={{gridTemplateColumns: "1fr 320px", gap: 14, alignItems: "flex-start"}}>
        <div>
          <Card padded={false} className="mb-lg" flush>
            <div style={{padding: "14px 16px"}}>
              <Workflow steps={["จัดทำ", "อนุมัติ", "จ่ายเงิน + เซ็นรับ", "บันทึกบัญชี"]} current={rv.status === "จ่ายแล้ว" ? 3 : 1}/>
            </div>
          </Card>
          <RVPaper rv={rv}/>
        </div>
        <div style={{display: "flex", flexDirection: "column", gap: 14}}>
          <Card title="สถานะ" right={<Badge>{rv.status}</Badge>}>
            <div style={{display: "flex", flexDirection: "column", gap: 8, fontSize: 13}}>
              <div style={{display: "flex", justifyContent: "space-between"}}><span className="muted">เลขที่</span><span className="mono">{rv.no}</span></div>
              <div style={{display: "flex", justifyContent: "space-between"}}><span className="muted">วันที่</span><span>{rv.date}</span></div>
              <div style={{display: "flex", justifyContent: "space-between"}}><span className="muted">วิธีจ่าย</span><span>{rv.method}</span></div>
              <div style={{display: "flex", justifyContent: "space-between"}}><span className="muted">จำนวนเงิน</span><span className="amount">฿{fmt0(rv.amount)}</span></div>
              {rv.wht > 0 && <div style={{display: "flex", justifyContent: "space-between"}}><span className="muted">หัก ณ ที่จ่าย</span><span className="amount">฿{fmt0(rv.wht)}</span></div>}
              {rv.ref && rv.ref !== "—" && <div style={{display: "flex", justifyContent: "space-between"}}><span className="muted">อ้างอิง</span><span className="mono" style={{fontSize: 12}}>{rv.ref}</span></div>}
            </div>
          </Card>
          <Card title="ผู้รับเงิน">
            <div style={{fontSize: 13, lineHeight: 1.7}}>
              <div style={{fontWeight: 500, marginBottom: 4}}>{rv.payee}</div>
              {rv.idcard && <div className="muted">บัตรประชาชน <span className="mono">{rv.idcard}</span></div>}
              {rv.address && <div className="muted" style={{fontSize: 12}}>{rv.address}</div>}
            </div>
          </Card>
          <window.SlipUpload voucherNo={rv.no}/>
          <Card title="ประวัติ">
            <div style={{display: "flex", flexDirection: "column", gap: 8, fontSize: 12.5, color: "var(--ink-3)"}}>
              <div><b style={{color: "var(--ink-1)"}}>{rv.payer || "ดวงใจ บ."}</b> จัดทำ · {rv.date}</div>
              <div><b style={{color: "var(--ink-1)"}}>ปิยะ ศ.</b> อนุมัติ · {rv.date}</div>
              {rv.status === "จ่ายแล้ว" && <div><b style={{color: "var(--ink-1)"}}>{rv.payee}</b> เซ็นรับเงิน · {rv.date}</div>}
            </div>
          </Card>
        </div>
      </div>
    </>
  );
}

// =============== Create drawer (form + live preview) ===============
function ReceiptVoucherCreate({ onClose }) {
  const C = window.SSSData.Company;
  const { Btn } = window.UI;
  const [no, setNo] = useStateRV("RV-2569-0024");
  const [date, setDate] = useStateRV("22 พ.ค. 2569");
  const [payee, setPayee] = useStateRV("");
  const [idcard, setIdcard] = useStateRV("");
  const [address, setAddress] = useStateRV("");
  const [method, setMethod] = useStateRV("เงินสด");
  const [ref, setRef] = useStateRV("");
  const [wht, setWht] = useStateRV(0);
  const [lines, setLines] = useStateRV([{ id: 1, desc: "", amount: 0 }]);

  const addLine = () => setLines(ls => [...ls, { id: Date.now(), desc: "", amount: 0 }]);
  const delLine = (id) => setLines(ls => ls.length > 1 ? ls.filter(l => l.id !== id) : ls);
  const updLine = (id, patch) => setLines(ls => ls.map(l => l.id === id ? { ...l, ...patch } : l));

  const rv = {
    no, date, payee: payee || "(ชื่อผู้รับเงิน)", idcard, address, method, ref,
    wht: Number(wht) || 0, payer: C.currentUser.name,
    lines: lines.map(l => ({ desc: l.desc, amount: Number(l.amount) || 0 })),
    amount: lines.reduce((s, l) => s + (Number(l.amount) || 0), 0)
  };

  const save = () => { onClose && onClose(); window.toast && window.toast(`บันทึกใบสำคัญรับเงิน ${no} แล้ว`); };
  const saveAndPrint = () => { setTimeout(() => window.printDocPaperWithOptions(), 250); };

  return (
    <>
      <div className="scrim" onClick={onClose}/>
      <div className="drawer wide newdoc-drawer" style={{width: 1040}}>
        <div className="drawer-head">
          <I.receipt size={16}/>
          <h3>ออกใบสำคัญรับเงิน</h3>
          <span className="mono muted" style={{fontSize: 12}}>{no}</span>
          <span className="spacer"/>
          <button className="icon-btn" onClick={onClose}><I.close size={14}/></button>
        </div>
        <div className="drawer-body" style={{padding: 0, display: "grid", gridTemplateColumns: "1fr 1fr"}}>
          {/* Form */}
          <div style={{padding: 18, borderRight: "1px solid var(--line)", overflowY: "auto"}}>
            <div className="h2 mb">ข้อมูลเอกสาร</div>
            <div className="field-row cols-2 mb">
              <div className="field"><label>เลขที่</label><input className="input mono" value={no} onChange={e=>setNo(e.target.value)}/></div>
              <div className="field"><label>วันที่</label><input className="input" value={date} onChange={e=>setDate(e.target.value)}/></div>
            </div>

            <div className="h2 mt-lg mb">ผู้รับเงิน</div>
            <div className="field mb"><label>ชื่อ–นามสกุล</label><input className="input" value={payee} onChange={e=>setPayee(e.target.value)} placeholder="เช่น นายสมบัติ แสงทอง"/></div>
            <div className="field-row cols-2 mb">
              <div className="field"><label>เลขบัตรประชาชน</label><input className="input mono" value={idcard} onChange={e=>setIdcard(e.target.value)} placeholder="x xxxx xxxxx xx x"/></div>
              <div className="field"><label>อ้างอิง (JOB/PO)</label><input className="input mono" value={ref} onChange={e=>setRef(e.target.value)} placeholder="—"/></div>
            </div>
            <div className="field mb"><label>ที่อยู่</label><textarea className="textarea" value={address} onChange={e=>setAddress(e.target.value)} style={{minHeight: 54}} placeholder="ที่อยู่ผู้รับเงิน"/></div>

            <div className="h2 mt-lg mb" style={{display: "flex", alignItems: "center"}}>
              <span>รายการ</span><span className="spacer"/>
              <Btn size="sm" icon={I.plus} onClick={addLine}>เพิ่มรายการ</Btn>
            </div>
            <div style={{display: "flex", flexDirection: "column", gap: 8}}>
              {lines.map((l, i) => (
                <div key={l.id} style={{display: "grid", gridTemplateColumns: "18px 1fr 110px 30px", gap: 6, alignItems: "center"}}>
                  <span style={{fontSize: 11, color: "var(--ink-3)"}}>#{i+1}</span>
                  <input className="input" placeholder="รายละเอียด" value={l.desc} onChange={e=>updLine(l.id, { desc: e.target.value })}/>
                  <input className="input" type="number" placeholder="จำนวนเงิน" value={l.amount} onChange={e=>updLine(l.id, { amount: e.target.value })} style={{textAlign: "right"}}/>
                  <button className="icon-btn" onClick={() => delLine(l.id)} title="ลบ"><I.trash size={12}/></button>
                </div>
              ))}
            </div>

            <div className="field-row cols-2 mt-lg">
              <div className="field"><label>วิธีจ่ายเงิน</label>
                <select className="input" value={method} onChange={e=>setMethod(e.target.value)}>
                  <option>เงินสด</option><option>โอน · KBank</option><option>โอน · BBL</option><option>เช็ค</option><option>เงินสดย่อย</option>
                </select>
              </div>
              <div className="field"><label>หัก ณ ที่จ่าย (ถ้ามี)</label><input className="input" type="number" value={wht} onChange={e=>setWht(e.target.value)} style={{textAlign: "right"}}/></div>
            </div>
          </div>

          {/* Live preview */}
          <div style={{padding: 18, overflowY: "auto", background: "var(--surface-2)"}}>
            <div className="h2 mb muted" style={{display: "flex", alignItems: "center", gap: 6}}>
              <I.doc size={14}/> ตัวอย่างเอกสาร (พิมพ์ได้)
            </div>
            <RVPaper rv={rv}/>
          </div>
        </div>
        <div className="drawer-foot">
          <Btn kind="ghost" onClick={onClose}>ยกเลิก</Btn>
          <Btn kind="ghost">บันทึกร่าง</Btn>
          <Btn icon={I.print} onClick={saveAndPrint}>บันทึก + พิมพ์</Btn>
          <Btn kind="primary" icon={I.check} onClick={save}>บันทึก</Btn>
        </div>
      </div>
    </>
  );
}

function ReceiptVoucherHost() {
  const [open, setOpen] = useStateRV(false);
  useEffectRV(() => { window.openReceiptVoucher = () => setOpen(true); }, []);
  if (!open) return null;
  return <ReceiptVoucherCreate onClose={() => setOpen(false)}/>;
}

window.ReceiptVouchers = ReceiptVouchers;
window.ReceiptVoucherDetail = ReceiptVoucherDetail;
window.ReceiptVoucherHost = ReceiptVoucherHost;
window.RVPaper = RVPaper;
