/* global React, I, UI, SSSData */
// =============== สินค้าที่ต้องการ / รอซื้อ — Purchase Requests ===============
const { useState: useStatePR, useEffect: useEffectPR } = React;

function prList() { return window.SSSData.PurchaseRequests || []; }
function prSaveList(list) {
  window.SSSData.PurchaseRequests = list;
  window.dispatchEvent(new Event("sss-purchase-requests-changed"));
}
function prToday() {
  const d = new Date();
  const m = ["ม.ค.", "ก.พ.", "มี.ค.", "เม.ย.", "พ.ค.", "มิ.ย.", "ก.ค.", "ส.ค.", "ก.ย.", "ต.ค.", "พ.ย.", "ธ.ค."];
  return `${d.getDate()} ${m[d.getMonth()]} ${d.getFullYear() + 543}`;
}
function prProjects() {
  const D = window.SSSData;
  return [...(window.ProjX && window.ProjX.upLoad ? window.ProjX.upLoad() : []), ...(D.Projects || [])];
}

// API กลาง — ให้หน้าค่าใช้จ่ายดึงรายการรอซื้อ + mark ว่าซื้อแล้ว(ผูกกับค่าใช้จ่าย) + เพิ่มใหม่
window.PurchaseRequests = {
  pending(projectCode) {
    return prList().filter(r => r.status !== "ซื้อแล้ว" && (!projectCode || r.projectCode === projectCode));
  },
  get(id) { return prList().find(r => r.id === id); },
  add(rec) {
    const r = { qty: 1, unit: "ชิ้น", ...rec, id: "PR-" + Date.now(), status: "รอซื้อ", by: window.actorName ? window.actorName() : "", date: prToday() };
    prSaveList([r, ...prList()]);
    window.logActivity && window.logActivity("ขอซื้อสินค้า", `${r.name} ${r.qty} ${r.unit}${r.projectCode ? " → " + r.projectCode : ""}`, "create");
    return r;
  },
  markBought(ids, expenseRef) {
    const set = new Set(ids);
    prSaveList(prList().map(r => set.has(r.id) ? { ...r, status: "ซื้อแล้ว", expenseRef: expenseRef || r.expenseRef, boughtAt: prToday() } : r));
  }
};

// ---------- Modal เพิ่ม/แก้ไขรายการรอซื้อ ----------
function PREditModal({ initial, onClose, onSave }) {
  const { Btn, ProductAutocomplete } = window.UI;
  const D = window.SSSData;
  const projects = prProjects();
  const [f, setF] = useStatePR(initial || {
    name: "", qty: 1, unit: "ชิ้น", vendor: "", projectCode: "", est: "", note: ""
  });
  const upd = (k, v) => setF(p => ({ ...p, [k]: v }));
  const save = () => {
    if (!f.name.trim()) { window.toast && window.toast("กรุณาใส่ชื่อสินค้าที่ต้องการซื้อ"); return; }
    const proj = projects.find(p => p.code === f.projectCode);
    onSave({ ...f, name: f.name.trim(), projectName: proj ? proj.name : "" });
    onClose();
  };
  return (
    <div className="scrim" style={{display: "flex", alignItems: "center", justifyContent: "center", padding: 18, zIndex: 220}} onClick={onClose}>
      <div style={{background: "var(--surface)", borderRadius: 14, width: 480, maxWidth: "96vw", maxHeight: "94vh", overflow: "auto"}} onClick={e => e.stopPropagation()}>
        <div style={{padding: "16px 20px 12px", borderBottom: "1px solid var(--line)", display: "flex", alignItems: "center"}}>
          <div style={{fontSize: 15, fontWeight: 700, flex: 1}}>{initial ? "แก้ไขรายการรอซื้อ" : "เพิ่มสินค้าที่ต้องการซื้อ"}</div>
          <button className="icon-btn" onClick={onClose}><I.close size={14}/></button>
        </div>
        <div style={{padding: "14px 20px", display: "flex", flexDirection: "column", gap: 12}}>
          <div className="field"><label>สินค้าที่ต้องการ *</label>
            <ProductAutocomplete value={f.name} placeholder="พิมพ์ชื่อสินค้า — มี/ไม่มีในคลังก็ได้"
              onChange={v => upd("name", v)} onPick={p => setF(prev => ({ ...prev, name: p.name, unit: p.unit || prev.unit, est: p.cost || p.price || prev.est }))}/>
          </div>
          <div className="field-row cols-2" style={{display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10}}>
            <div className="field"><label>จำนวน</label><input className="input" type="number" min="0" step="any" value={f.qty} onChange={e => upd("qty", +e.target.value || 0)}/></div>
            <div className="field"><label>หน่วย</label><input className="input" value={f.unit} onChange={e => upd("unit", e.target.value)} placeholder="แผ่น/เส้น/ชิ้น"/></div>
          </div>
          <div className="field"><label>ซื้อจาก (ผู้ขาย/ร้าน)</label><input className="input" value={f.vendor} onChange={e => upd("vendor", e.target.value)} placeholder="เช่น ร้านสแตนเลสสามพราน"/></div>
          <div className="field-row cols-2" style={{display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10}}>
            <div className="field"><label>ใช้กับโปรเจกต์</label>
              <select className="input mono" value={f.projectCode} onChange={e => upd("projectCode", e.target.value)}>
                <option value="">— ไม่ระบุ —</option>
                {projects.map(p => <option key={p.code} value={p.code}>{p.code} · {p.name}</option>)}
              </select>
            </div>
            <div className="field"><label>ราคาประมาณ/รวม (บาท)</label><input className="input" type="number" min="0" value={f.est} onChange={e => upd("est", e.target.value)} placeholder="ไม่บังคับ"/></div>
          </div>
          <div className="field"><label>หมายเหตุ</label><textarea className="textarea" value={f.note} onChange={e => upd("note", e.target.value)} style={{minHeight: 50}} placeholder="สเปก/ยี่ห้อ/ความเร่งด่วน"/></div>
        </div>
        <div style={{padding: "12px 20px", borderTop: "1px solid var(--line)", background: "var(--surface-2)", display: "flex", gap: 8, justifyContent: "flex-end"}}>
          <Btn kind="ghost" onClick={onClose}>ยกเลิก</Btn>
          <Btn kind="primary" icon={I.check} onClick={save}>{initial ? "บันทึก" : "เพิ่มรายการ"}</Btn>
        </div>
      </div>
    </div>
  );
}

function PurchaseRequestsPage({ navigate }) {
  const { Btn, Badge, Card, PageHead, Stat, Tabs } = window.UI;
  const fmt0 = window.UI.fmt0;
  const [, force] = useStatePR(0);
  const refresh = () => force(n => n + 1);
  useEffectPR(() => {
    const h = () => refresh();
    ["sss-purchase-requests-changed", "sss-data-synced"].forEach(e => window.addEventListener(e, h));
    return () => ["sss-purchase-requests-changed", "sss-data-synced"].forEach(e => window.removeEventListener(e, h));
  }, []);
  const [tab, setTab] = useStatePR("pending");
  const [showNew, setShowNew] = useStatePR(false);
  const [editing, setEditing] = useStatePR(null);

  const all = prList();
  const pending = all.filter(r => r.status !== "ซื้อแล้ว");
  const bought = all.filter(r => r.status === "ซื้อแล้ว");
  const estTotal = pending.reduce((s, r) => s + (+r.est || 0), 0);

  const addPR = (f) => {
    window.PurchaseRequests.add(f);
    window.toast && window.toast("เพิ่มรายการรอซื้อแล้ว");
  };
  const patchPR = (id, patch) => prSaveList(all.map(r => r.id === id ? { ...r, ...patch } : r));
  const removePR = async (r) => {
    const ok = await (window.confirmDelete ? window.confirmDelete(`รายการรอซื้อ ${r.name}`, r.projectName || "") : Promise.resolve(confirm("ลบ?")));
    if (!ok) return;
    window.markDeleted && window.markDeleted("PurchaseRequests", r.id || r.no);   // กัน poll ดึงกลับมาก่อน save
    prSaveList(all.filter(x => x.id !== r.id));
  };
  const markBought = (r) => { patchPR(r.id, { status: "ซื้อแล้ว", boughtAt: prToday() }); window.toast && window.toast(`ทำเครื่องหมายซื้อแล้ว — บันทึกค่าใช้จ่ายได้ที่หน้าโปรเจกต์`); };

  const rows = tab === "pending" ? pending : tab === "bought" ? bought : all;

  return (
    <>
      <PageHead title="สินค้าที่ต้องการ / รอซื้อ"
        sub="ลงรายการสินค้าที่ต้องสั่งซื้อ — จำนวน ซื้อจากไหน ใช้กับโปรเจกต์ใด · เชื่อมกับการเพิ่มค่าใช้จ่าย"
        right={<Btn icon={I.plus} kind="primary" onClick={() => setShowNew(true)}>เพิ่มรายการรอซื้อ</Btn>}/>

      <div className="stat-grid" style={{display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(170px, 1fr))", gap: 12, marginBottom: 16}}>
        <Stat label="รอซื้อ" value={pending.length} sub="ยังไม่ได้สั่งซื้อ" icon={I.cart || I.buy}/>
        <Stat label="ซื้อแล้ว" value={bought.length} sub="สั่ง/ซื้อเรียบร้อย" icon={I.check}/>
        <Stat label="มูลค่าประมาณ (รอซื้อ)" value={`฿${fmt0(estTotal)}`} sub="จากราคาที่ประเมินไว้" icon={I.money}/>
      </div>

      <Tabs items={[
        { key: "pending", label: "รอซื้อ", count: pending.length },
        { key: "bought", label: "ซื้อแล้ว", count: bought.length },
        { key: "all", label: "ทั้งหมด", count: all.length }
      ]} active={tab} onChange={setTab}/>

      <Card flush style={{marginTop: 14}}>
        {rows.length === 0 ? (
          <div style={{padding: 30, textAlign: "center", color: "var(--ink-3)", fontSize: 12.5}}>ยังไม่มีรายการ — กด "เพิ่มรายการรอซื้อ" เพื่อเริ่ม</div>
        ) : (
          <div className="table-wrap">
            <table className="t">
              <thead><tr><th>สินค้า</th><th className="right">จำนวน</th><th>ซื้อจาก</th><th>ใช้กับโปรเจกต์</th><th className="right">ราคาประมาณ</th><th>ผู้ขอ</th><th>สถานะ</th><th></th></tr></thead>
              <tbody>
                {rows.map(r => (
                  <tr key={r.id}>
                    <td><b>{r.name}</b>{r.note ? <div style={{fontSize: 11, color: "var(--ink-3)"}}>{r.note}</div> : null}</td>
                    <td className="right">{r.qty} {r.unit}</td>
                    <td className="muted">{r.vendor || "—"}</td>
                    <td>{r.projectCode ? <span className="mono" style={{fontSize: 12}}>{r.projectCode}</span> : <span className="muted">—</span>}{r.expenseRef ? <Badge tone="info" style={{marginLeft: 4}}>ผูกค่าใช้จ่าย</Badge> : null}</td>
                    <td className="right amount">{r.est ? "฿" + fmt0(+r.est) : "—"}</td>
                    <td className="muted" style={{fontSize: 12}}>{r.by || "—"}<div style={{fontSize: 11, color: "var(--ink-4)"}}>{r.date}</div></td>
                    <td><Badge tone={r.status === "ซื้อแล้ว" ? "success" : "warning"}>{r.status}</Badge></td>
                    <td>
                      <div style={{display: "flex", gap: 2}}>
                        {r.status !== "ซื้อแล้ว" && <button className="icon-btn" title="ทำเครื่องหมายซื้อแล้ว" onClick={() => markBought(r)}><I.check size={13}/></button>}
                        <button className="icon-btn" title="แก้ไข" onClick={() => setEditing(r)}><I.edit size={13}/></button>
                        <button className="icon-btn" title="ลบ" onClick={() => removePR(r)}><I.trash size={13}/></button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </Card>

      {showNew && <PREditModal onClose={() => setShowNew(false)} onSave={addPR}/>}
      {editing && <PREditModal initial={editing} onClose={() => setEditing(null)} onSave={(f) => patchPR(editing.id, f)}/>}
    </>
  );
}

window.PurchaseRequestsPage = PurchaseRequestsPage;
window.PREditModal = PREditModal;
