// หน้าออกใบกำกับภาษี / ใบเสร็จอย่างเป็นทางการ
function InvoicesPage({ ui, user }) {
  const { st } = useStore();
  const toast = useToast();
  const [mode, setMode] = React.useState("view"); // "view" | "edit" | "list"
  const [inv, setInv] = React.useState(null);
  const [list, setList] = React.useState([]);
  const [searchInv, setSearchInv] = React.useState("");
  const [printInv, setPrintInv] = React.useState(null);

  // ── ข้อมูลร้านค้า — ดึงจากตั้งค่าระบบ (อ่านอย่างเดียว) ──
  const seller = {
    name: st.settings?.name || "SSPHONE",
    taxId: st.settings?.taxId || "",
    addr: st.settings?.addr || "",
    tel: st.settings?.tel || "",
  };

  // โหลดรายการ + แสดงใบกำกับภาษีล่าสุดทุกครั้งที่เปิด
  React.useEffect(() => {
    const invs = JSON.parse(localStorage.getItem("ssphone-invoices") || "[]");
    invs.sort((a, b) => (b.ts || 0) - (a.ts || 0));
    setList(invs);
    if (invs.length > 0) { setInv(invs[0]); setMode("view"); }
    else { setMode("list"); }
  }, []);

  const persist = (invs) => {
    invs.sort((a, b) => (b.ts || 0) - (a.ts || 0));
    localStorage.setItem("ssphone-invoices", JSON.stringify(invs));
    setList(invs);
  };

  const nextNo = () => list.reduce((m, iv) => Math.max(m, iv.no || 0), 0) + 1;
  const mkId = (no) => `INVTAX-${String(no).padStart(4, "0")}`;

  const blankInvoice = () => {
    const no = nextNo();
    return {
      id: mkId(no), no, ts: Date.now(), refInv: "",
      customerName: "", customerTaxId: "", customerAddress: "",
      items: [{ description: "", qty: 1, unitPrice: 0, amount: 0 }],
      discount: 0, notes: "", createdBy: user.id,
    };
  };

  const createBlank = () => { setInv(blankInvoice()); setMode("edit"); };

  // ── ค้นหาใบเสร็จ INV แล้วดึงข้อมูลมาออกใบกำกับภาษี ──
  const doSearchInv = () => {
    const q = searchInv.trim().toUpperCase();
    if (!q) { toast("กรอกเลขที่ใบเสร็จ INV", "danger"); return; }
    // ถ้าเคยออกใบกำกับภาษีจากใบเสร็จนี้แล้ว → เปิดอันเดิม
    const existing = list.find((iv) => (iv.refInv || "").toUpperCase() === q);
    if (existing) { setInv(existing); setMode("view"); setSearchInv(""); toast("เปิดใบกำกับภาษีที่ออกไว้แล้วของ " + existing.refInv); return; }
    const sale = st.sales.find((s) => s.id.toUpperCase() === q) || st.sales.find((s) => s.id.toUpperCase().includes(q));
    if (!sale) { toast("ไม่พบใบเสร็จ " + searchInv, "danger"); return; }
    const no = nextNo();
    setInv({
      id: mkId(no), no, ts: Date.now(), refInv: sale.id,
      customerName: (sale.customer || "").replace(/\s*\d[\d\- ]{6,}\d/, "").trim() || sale.customer || "",
      customerTaxId: "", customerAddress: "",
      items: sale.items.map((it) => {
        const p = prodOf(st, it.productId);
        const base = p ? p.name : ("สินค้า " + it.productId);
        const sp = specOf(st, p);
        return { description: sp ? base + " · " + sp : base, qty: it.qty, unitPrice: it.price, amount: it.qty * it.price };
      }),
      discount: sale.discount || 0, notes: "", createdBy: user.id,
    });
    setMode("edit");
    setSearchInv("");
    toast("ดึงข้อมูลจากใบเสร็จ " + sale.id + " แล้ว");
  };

  const upd = (field, value) => setInv((x) => ({ ...x, [field]: value }));
  const addItem = () => setInv((x) => ({ ...x, items: [...(x.items || []), { description: "", qty: 1, unitPrice: 0, amount: 0 }] }));
  const updItem = (idx, field, value) => setInv((x) => {
    const items = [...x.items];
    items[idx] = { ...items[idx], [field]: value };
    if (field === "qty" || field === "unitPrice") items[idx].amount = (Number(items[idx].qty) || 0) * (Number(items[idx].unitPrice) || 0);
    return { ...x, items };
  });
  const rmItem = (idx) => setInv((x) => ({ ...x, items: x.items.filter((_, i) => i !== idx) }));

  const saveInvoice = () => {
    if (!inv.customerName || !inv.items.some((i) => i.description)) { toast("กรอกชื่อลูกค้า และรายการอย่างน้อย 1 รายการ", "danger"); return; }
    const cleaned = { ...inv, items: inv.items.filter((i) => i.description) };
    const invs = list.filter((x) => x.id !== cleaned.id);
    invs.push(cleaned);
    persist(invs);
    setInv(cleaned);
    setMode("view");
    toast("บันทึกใบกำกับภาษีสำเร็จ");
  };

  const openInvoice = (id) => { const f = list.find((x) => x.id === id); if (f) { setInv(f); setMode("view"); } };
  const deleteInvoice = (id) => {
    if (!confirm("ลบใบกำกับภาษีนี้หรือไม่?")) return;
    const invs = list.filter((x) => x.id !== id);
    persist(invs);
    if (inv && inv.id === id) { if (invs.length) { setInv(invs[0]); setMode("view"); } else { setInv(null); setMode("list"); } }
    toast("ลบแล้ว");
  };

  const subtotal = inv?.items?.reduce((a, i) => a + (i.amount || 0), 0) || 0;
  const afterDisc = subtotal - (Number(inv?.discount) || 0);
  const vat = Math.round(afterDisc / 1.07 * 0.07);
  const beforeVat = afterDisc - vat;

  const SearchBar = () => (
    <Card style={{ padding: 14, display: "flex", gap: 10, alignItems: "center", flexWrap: "wrap" }}>
      <span style={{ fontSize: 13, fontWeight: 700, color: T.sub }}>ค้นหาใบเสร็จ</span>
      <div style={{ flex: 1, minWidth: 220, display: "flex", gap: 8 }}>
        <TextInput value={searchInv} onChange={(e) => setSearchInv(e.target.value)} onKeyDown={(e) => { if (e.key === "Enter") doSearchInv(); }} placeholder="เลขที่ใบเสร็จ เช่น INV-2506-0218" style={{ flex: 1 }} />
        <Btn onClick={doSearchInv}>🔍 ค้นหา &amp; ออกใบกำกับภาษี</Btn>
      </div>
      <Btn kind="soft" onClick={createBlank}>⊕ สร้างเปล่า</Btn>
      <Btn kind="ghost" onClick={() => setMode("list")}>📋 ทั้งหมด ({list.length})</Btn>
    </Card>
  );

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
      <SearchBar />

      {mode === "list" && (
        <Card style={{ padding: 0, overflow: "hidden" }}>
          {list.length === 0 ? (
            <EmptyState text="ยังไม่มีใบกำกับภาษี — ค้นหาใบเสร็จ INV ด้านบนเพื่อออกใบแรก" />
          ) : (
            <div style={{ display: "flex", flexDirection: "column" }}>
              {list.map((iv) => {
                const t = iv.items?.reduce((a, i) => a + (i.amount || 0), 0) - (Number(iv.discount) || 0) || 0;
                return (
                  <div key={iv.id} className="ss-row" style={{ display: "flex", alignItems: "center", gap: 14, padding: "12px 16px", borderBottom: `1px solid ${T.rowBorder}`, cursor: "pointer" }} onClick={() => openInvoice(iv.id)}>
                    <div style={{ minWidth: 0, flex: 1 }}>
                      <div style={{ fontWeight: 700, fontSize: 13, fontFamily: "monospace" }}>{iv.id}{iv.refInv && <span style={{ color: T.sub, fontWeight: 500 }}> · อ้างอิง {iv.refInv}</span>}</div>
                      <div style={{ fontSize: 12, color: T.sub }}>{iv.customerName} · {fmtDate(iv.ts)}</div>
                    </div>
                    <div style={{ textAlign: "right", minWidth: 100 }}>
                      <div style={{ fontFamily: T.headFont, fontWeight: 800, fontSize: 14 }}>{fmtMoney(t)}</div>
                      <div style={{ fontSize: 11, color: T.sub }}>{iv.items?.length || 0} รายการ</div>
                    </div>
                    <Btn sm kind="ghost" onClick={(e) => { e.stopPropagation(); deleteInvoice(iv.id); }}>✕</Btn>
                  </div>
                );
              })}
            </div>
          )}
        </Card>
      )}

      {(mode === "edit" || mode === "view") && inv && (
        <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
          <div style={{ display: "flex", gap: 10, alignItems: "center" }}>
            <div>
              <h2 style={{ fontSize: 18, fontWeight: 800, margin: 0, fontFamily: T.headFont }}>{mode === "edit" ? "ออกใบกำกับภาษี" : "ใบกำกับภาษี"} <span style={{ fontFamily: "monospace", color: T.primary }}>{inv.id}</span></h2>
              {inv.refInv && <div style={{ fontSize: 12, color: T.sub, marginTop: 2 }}>อ้างอิงใบเสร็จ: <b style={{ fontFamily: "monospace" }}>{inv.refInv}</b></div>}
            </div>
            <div style={{ marginLeft: "auto", display: "flex", gap: 8 }}>
              {mode === "view" && <Btn kind="warn" style={{ background: "#E8833A", color: "#fff" }} onClick={() => setPrintInv(inv)}>⎙ พิมพ์ใบกำกับภาษี</Btn>}
              {mode === "view" && <Btn kind="soft" onClick={() => setMode("edit")}>✎ แก้ไข</Btn>}
              {mode === "edit" && <Btn kind="ok" onClick={saveInvoice}>💾 บันทึก</Btn>}
            </div>
          </div>

          <Card style={{ padding: 18 }}>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 18, marginBottom: 18, paddingBottom: 16, borderBottom: `1px solid ${T.border}` }}>
              {/* ผู้ขาย — อ่านจากตั้งค่าระบบ */}
              <div>
                <div style={{ fontSize: 11, color: T.sub, fontWeight: 700, marginBottom: 8, letterSpacing: 0.3 }}>ผู้ออกใบกำกับภาษี (ร้านค้า)</div>
                <div style={{ fontSize: 12.8, lineHeight: 1.7 }}>
                  <div style={{ fontWeight: 800, fontSize: 15, fontFamily: T.headFont }}>{seller.name}</div>
                  <div>เลขประจำตัวผู้เสียภาษี: <b>{seller.taxId || "—"}</b></div>
                  <div style={{ whiteSpace: "pre-wrap", color: T.sub }}>{seller.addr}</div>
                  <div style={{ color: T.sub }}>โทร: {seller.tel}</div>
                </div>
              </div>

              {/* ลูกค้า */}
              <div>
                <div style={{ fontSize: 11, color: T.sub, fontWeight: 700, marginBottom: 8, letterSpacing: 0.3 }}>ข้อมูลลูกค้า</div>
                {mode === "edit" ? (
                  <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                    <Field label="ชื่อลูกค้า / บริษัท" req><TextInput value={inv.customerName} onChange={(e) => upd("customerName", e.target.value)} /></Field>
                    <Field label="เลขประจำตัวผู้เสียภาษี (ถ้ามี)"><TextInput value={inv.customerTaxId} onChange={(e) => upd("customerTaxId", e.target.value)} /></Field>
                    <Field label="ที่อยู่ (ถ้ามี)"><TextArea value={inv.customerAddress} onChange={(e) => upd("customerAddress", e.target.value)} style={{ fontSize: 12, minHeight: 54 }} /></Field>
                  </div>
                ) : (
                  <div style={{ fontSize: 12.8, lineHeight: 1.7 }}>
                    <div style={{ fontWeight: 800, fontSize: 15, fontFamily: T.headFont }}>{inv.customerName}</div>
                    {inv.customerTaxId && <div>เลขประจำตัวผู้เสียภาษี: <b>{inv.customerTaxId}</b></div>}
                    {inv.customerAddress && <div style={{ whiteSpace: "pre-wrap", color: T.sub }}>{inv.customerAddress}</div>}
                    <div style={{ color: T.sub }}>วันที่: {fmtDate(inv.ts)}</div>
                  </div>
                )}
              </div>
            </div>

            {/* รายการ */}
            <div style={{ marginBottom: 16 }}>
              <div style={{ fontSize: 11, color: T.sub, fontWeight: 700, marginBottom: 10, letterSpacing: 0.3 }}>รายการสินค้า / บริการ</div>
              <div style={{ display: "grid", gridTemplateColumns: mode === "edit" ? "2fr 80px 110px 110px 36px" : "2fr 80px 110px 110px", gap: 8, fontSize: 12, marginBottom: 8, paddingBottom: 8, borderBottom: `1px solid ${T.border}`, color: T.sub }}>
                <div>รายการ</div>
                <div style={{ textAlign: "center" }}>จำนวน</div>
                <div style={{ textAlign: "right" }}>ราคา/หน่วย</div>
                <div style={{ textAlign: "right" }}>จำนวนเงิน</div>
                {mode === "edit" && <div></div>}
              </div>
              {inv.items?.map((item, idx) => (
                <div key={idx} style={{ display: "grid", gridTemplateColumns: mode === "edit" ? "2fr 80px 110px 110px 36px" : "2fr 80px 110px 110px", gap: 8, alignItems: "center", marginBottom: 7, fontSize: 13 }}>
                  {mode === "edit" ? (
                    <>
                      <TextInput value={item.description} onChange={(e) => updItem(idx, "description", e.target.value)} placeholder="อธิบายรายการ" />
                      <NumInput value={item.qty} onChange={(e) => updItem(idx, "qty", e.target.value)} style={{ textAlign: "center" }} />
                      <NumInput value={item.unitPrice} onChange={(e) => updItem(idx, "unitPrice", e.target.value)} style={{ textAlign: "right" }} />
                      <div style={{ textAlign: "right", fontWeight: 600 }}>{fmtMoney(item.amount || 0)}</div>
                      <Btn sm kind="ghost" onClick={() => rmItem(idx)}>✕</Btn>
                    </>
                  ) : (
                    <>
                      <div>{item.description}</div>
                      <div style={{ textAlign: "center" }}>{item.qty}</div>
                      <div style={{ textAlign: "right" }}>{fmtMoney(item.unitPrice)}</div>
                      <div style={{ textAlign: "right", fontWeight: 600 }}>{fmtMoney(item.amount || 0)}</div>
                    </>
                  )}
                </div>
              ))}
              {mode === "edit" && <Btn sm kind="soft" onClick={addItem} style={{ marginTop: 8 }}>+ เพิ่มรายการ</Btn>}
            </div>

            {/* สรุป */}
            <div style={{ display: "grid", gridTemplateColumns: "1fr 240px", gap: 20, alignItems: "start", paddingTop: 14, borderTop: `2px solid ${T.border}` }}>
              <div>
                {mode === "edit" ? (
                  <Field label="หมายเหตุ"><TextArea value={inv.notes} onChange={(e) => upd("notes", e.target.value)} placeholder="หมายเหตุเพิ่มเติม (ถ้ามี)" style={{ fontSize: 12, minHeight: 54 }} /></Field>
                ) : (inv.notes && (
                  <div>
                    <div style={{ fontSize: 11, color: T.sub, fontWeight: 700, marginBottom: 6 }}>หมายเหตุ</div>
                    <div style={{ fontSize: 12.8, whiteSpace: "pre-wrap" }}>{inv.notes}</div>
                  </div>
                ))}
              </div>

              <div style={{ fontSize: 13 }}>
                <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 8 }}>
                  <span style={{ color: T.sub }}>ยอดรวม:</span>
                  <span style={{ fontWeight: 600, fontFamily: T.headFont }}>{fmtMoney(subtotal)}</span>
                </div>
                {mode === "edit" ? (
                  <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 8, alignItems: "center", gap: 8 }}>
                    <span style={{ color: T.sub }}>ส่วนลด:</span>
                    <div style={{ width: 110 }}><NumInput value={inv.discount} onChange={(e) => upd("discount", e.target.value)} style={{ textAlign: "right" }} /></div>
                  </div>
                ) : ((Number(inv.discount) || 0) > 0 && (
                  <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 8 }}>
                    <span style={{ color: T.sub }}>ส่วนลด:</span>
                    <span style={{ fontWeight: 600, color: T.accent }}>−{fmtMoney(Number(inv.discount) || 0)}</span>
                  </div>
                ))}
                <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 8, paddingTop: 8, borderTop: `1px solid ${T.border}` }}>
                  <span style={{ color: T.sub }}>มูลค่าก่อน VAT:</span>
                  <span style={{ fontWeight: 600, fontFamily: T.headFont }}>{fmtMoney(beforeVat)}</span>
                </div>
                <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 10, paddingBottom: 10, borderBottom: `1px solid ${T.border}` }}>
                  <span style={{ color: T.sub }}>ภาษีมูลค่าเพิ่ม 7%:</span>
                  <span style={{ fontWeight: 600, fontFamily: T.headFont }}>{fmtMoney(vat)}</span>
                </div>
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
                  <span style={{ fontWeight: 800 }}>รวมทั้งสิ้น:</span>
                  <span style={{ fontFamily: T.headFont, fontWeight: 800, fontSize: 18, color: T.primary }}>{fmtMoney(afterDisc)}</span>
                </div>
              </div>
            </div>
          </Card>
        </div>
      )}

      <PrintModal open={!!printInv} onClose={() => setPrintInv(null)} kind="tax" data={printInv} />
    </div>
  );
}

window.InvoicesPage = InvoicesPage;
