// Procurement: PR/PO list with approval flow + create panel

function ProcurementPage({ lang }) {
  const [filter, setFilter] = useState("all"); // all | PR | PO | pending
  const [projectFilter, setProjectFilter] = useState("all");
  const [selected, setSelected] = useState(null);
  const toast = useToast();

  let base = filter === "all" ? PR_PO : filter === "pending" ? PR_PO.filter(x => x.status === "pending") : PR_PO.filter(x => x.type === filter);
  if (projectFilter !== "all") base = base.filter(x => x.project === projectFilter);
  const sort = useSort(base, "date", "desc");
  const data = sort.sorted;

  return (
    <div className="anim-fadein">
      <PageHeader
        title={lang === "th" ? "ระบบจัดซื้ออัตโนมัติ" : "Procurement (PR/PO)"}
        subtitle={lang === "th" ? "ใบขอซื้อ → ใบสั่งซื้อ → ตรวจรับของ — ติดตามทั้งกระบวนการ" : "PR → PO → Goods Receipt workflow"}
        actions={<>
          <button className="btn btn-sm"><I.upload /> {lang==="th"?"นำเข้า":"Import"}</button>
          <button className="btn btn-sm btn-primary"><I.plus /> {lang==="th"?"สร้าง PR":"New PR"}</button>
        </>}
      />

      {/* KPI strip */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(180px, 1fr))", gap: 12, marginBottom: 14 }}>
        <StatCard label={lang==="th"?"PR รออนุมัติ":"PR pending"} value={PR_PO.filter(x => x.type === "PR" && x.status === "pending").length} hint="⌛ 1.4 ชม. เฉลี่ย" icon="cart" />
        <StatCard label={lang==="th"?"PO เปิดอยู่":"Open POs"} value={PR_PO.filter(x => x.type === "PO" && x.status !== "received").length} icon="send" />
        <StatCard label={lang==="th"?"มูลค่าจัดซื้อเดือนนี้":"Spend MTD"} value={fmtTHB(PR_PO.reduce((a,x) => a + x.total, 0))} delta={-3.2} icon="cash" />
        <StatCard label={lang==="th"?"Vendor ใช้บ่อย":"Top vendors"} value="SCG · TSC · TOA" icon="people" />
      </div>

      <div style={{ display: "grid", gridTemplateColumns: selected != null ? "1.4fr 1fr" : "1fr", gap: 14, transition: "grid-template-columns .3s" }}>
        <div className="card" style={{ padding: 0, overflow: "hidden" }}>
          <div style={{ padding: 14, display: "flex", gap: 8, borderBottom: "1px solid var(--line)", flexWrap: "wrap" }}>
            {[
              { id: "all", th: "ทั้งหมด", en: "All" },
              { id: "PR", th: "PR", en: "PR" },
              { id: "PO", th: "PO", en: "PO" },
              { id: "pending", th: "รออนุมัติ", en: "Pending" },
            ].map((t) => (
              <button key={t.id} className="btn btn-sm" onClick={() => setFilter(t.id)}
                style={{
                  background: filter === t.id ? "rgba(40,72,255,0.18)" : "var(--glass-2)",
                  borderColor: filter === t.id ? "rgba(120,144,255,0.4)" : "var(--line)",
                  color: filter === t.id ? "var(--ink)" : "var(--ink-soft)",
                }}>{lang === "th" ? t.th : t.en}</button>
            ))}
            <div style={{ flex: 1 }} />
            <ProjectFilter value={projectFilter} onChange={setProjectFilter} lang={lang} />
            <button className="btn btn-sm"><I.filter /> {lang==="th"?"กรอง":"Filter"}</button>
          </div>
          <table className="table">
            <thead><tr>
              <SortTH label={lang==="th"?"เลขที่":"Code"} k="id" sort={sort} />
              <SortTH label={lang==="th"?"ประเภท":"Type"} k="type" sort={sort} />
              <SortTH label={lang==="th"?"โครงการ":"Project"} k="project" sort={sort} />
              <SortTH label={lang==="th"?"วันที่":"Date"} k="date" sort={sort} />
              <SortTH label={lang==="th"?"ผู้ขอ":"By"} k="requester" sort={sort} />
              <SortTH label={lang==="th"?"มูลค่า":"Total"} k="total" sort={sort} align="right" />
              <SortTH label="Status" k="status" sort={sort} />
            </tr></thead>
            <tbody>
              {data.map((x, i) => (
                <tr key={x.id} className="row-int" style={{ cursor: "pointer", background: selected === i ? "var(--glass-2)" : "transparent" }} onClick={() => setSelected(selected === i ? null : i)}>
                  <td className="mono" style={{ fontSize: 12, color: "var(--syk-blue-soft)" }}>{x.id}</td>
                  <td><span className="chip" style={{ background: x.type === "PR" ? "rgba(111,134,255,0.12)" : "rgba(74,222,128,0.12)", color: x.type === "PR" ? "var(--syk-blue-soft)" : "var(--emerald)" }}>{x.type}</span></td>
                  <td className="ink-soft mono" style={{ fontSize: 12 }}>{x.project}</td>
                  <td className="ink-soft mono" style={{ fontSize: 12 }}>{x.date}</td>
                  <td>{x.requester}</td>
                  <td className="mono" style={{ textAlign: "right", fontWeight: 600 }}>{fmtTHB(x.total)}</td>
                  <td><StatusBadge status={x.status} /></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        {selected != null && data[selected] && <PRDetail item={data[selected]} lang={lang} onClose={() => setSelected(null)} onApprove={() => { toast("อนุมัติ " + data[selected].id, "success"); setSelected(null); }} />}
      </div>
    </div>
  );
}

function PRDetail({ item, lang, onClose, onApprove }) {
  const flow = [
    { l: lang==="th"?"สร้าง PR":"Created", done: true,  who: item.requester, t: item.date },
    { l: lang==="th"?"PM อนุมัติ":"PM approved", done: ["approved","sent","received"].includes(item.status), who: "PM สมชาย", t: item.status !== "pending" ? "+2h" : "—" },
    { l: lang==="th"?"ออก PO":"PO issued", done: ["sent","received"].includes(item.status) || item.type === "PO", who: "จัดซื้อ", t: item.type === "PO" ? item.date : "—" },
    { l: lang==="th"?"ตรวจรับของ":"Goods received", done: item.status === "received", who: "โฟร์แมน", t: item.status === "received" ? "+3d" : "—" },
  ];
  return (
    <div className="card anim-fadein" style={{ position: "sticky", top: 80, maxHeight: "calc(100vh - 100px)", overflowY: "auto" }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 14 }}>
        <div>
          <div className="micro">{item.type}</div>
          <div className="mono" style={{ fontSize: 18, fontWeight: 700, color: "var(--syk-blue-soft)", marginTop: 4 }}>{item.id}</div>
        </div>
        <button className="btn btn-sm btn-ghost" onClick={onClose} style={{ padding: 0, width: 28, justifyContent: "center" }}><I.x /></button>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12, marginBottom: 16 }}>
        <div><div className="micro">Project</div><div style={{ fontSize: 12.5, marginTop: 4 }} className="mono">{item.project}</div></div>
        <div><div className="micro">Date</div><div style={{ fontSize: 12.5, marginTop: 4 }} className="mono">{item.date}</div></div>
        <div><div className="micro">By</div><div style={{ fontSize: 12.5, marginTop: 4 }}>{item.requester}</div></div>
        {item.vendor && <div><div className="micro">Vendor</div><div style={{ fontSize: 12.5, marginTop: 4 }}>{item.vendor}</div></div>}
      </div>

      <div className="micro" style={{ marginBottom: 10 }}>{lang==="th"?"Approval Flow":"Approval flow"}</div>
      <div style={{ display: "flex", flexDirection: "column", gap: 0, marginBottom: 18 }}>
        {flow.map((s, i) => (
          <div key={i} style={{ display: "flex", gap: 12, paddingBottom: 14 }}>
            <div style={{ position: "relative" }}>
              <div style={{
                width: 26, height: 26, borderRadius: "50%",
                background: s.done ? "linear-gradient(135deg, #4ade80, #22c55e)" : "var(--glass-3)",
                border: s.done ? "0" : "1px solid var(--line)",
                display: "flex", alignItems: "center", justifyContent: "center",
                color: "white", fontSize: 12,
              }}>{s.done ? <I.check size={14} /> : i + 1}</div>
              {i < flow.length - 1 && <div style={{ position: "absolute", left: 12.5, top: 28, width: 1.5, height: 22, background: s.done && flow[i+1].done ? "var(--emerald)" : "var(--line)" }} />}
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 12.5, fontWeight: 500 }}>{s.l}</div>
              <div style={{ fontSize: 11, color: "var(--ink-mute)", marginTop: 2 }}>{s.who} · {s.t}</div>
            </div>
          </div>
        ))}
      </div>

      <div style={{ padding: 14, background: "var(--glass-2)", borderRadius: 10, marginBottom: 16 }}>
        <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 4 }}><span className="ink-soft">{lang==="th"?"จำนวนรายการ":"Items"}</span><span className="mono">{item.items}</span></div>
        <div style={{ display: "flex", justifyContent: "space-between", fontSize: 16, fontWeight: 700 }}><span className="ink-soft" style={{ fontWeight: 500, fontSize: 13 }}>{lang==="th"?"รวม":"Total"}</span><span className="mono">{fmtTHB(item.total)}</span></div>
      </div>

      {item.status === "pending" && (
        <div style={{ display: "flex", gap: 8 }}>
          <button className="btn" style={{ flex: 1, justifyContent: "center", color: "var(--rose)" }}><I.x /> {lang==="th"?"ปฏิเสธ":"Reject"}</button>
          <button className="btn btn-primary" style={{ flex: 1, justifyContent: "center" }} onClick={onApprove}><I.check /> {lang==="th"?"อนุมัติ":"Approve"}</button>
        </div>
      )}
      {item.status !== "pending" && (
        <button className="btn" style={{ width: "100%", justifyContent: "center" }}><I.print /> {lang==="th"?"พิมพ์เอกสาร":"Print document"}</button>
      )}
    </div>
  );
}

window.ProcurementPage = ProcurementPage;
