/* global React, I, UI, SSSData */
// =============== จัดการบัญชีธนาคาร · Bank Accounts ===============
// เพิ่ม/แก้ไขบัญชีเงินสด-ธนาคารของบริษัท · เชื่อมกับผังบัญชี (ระบบบัญชีและภาษี)
const { useState: useStateBA, useEffect: useEffectBA } = React;

function baEmptyAcc() {
  return { id: "ACC" + Date.now(), code: "", name: "", short: "", detail: "", emoji: "🏦", kind: "ธนาคาร" };
}

function BankAccountsPage({ navigate }) {
  const { Btn, Badge, Card, PageHead, Stat, fmt0 } = window.UI;
  const [accounts, setAccounts] = useStateBA(() => window.BankAccountsStore ? window.BankAccountsStore.load() : []);
  const [edit, setEdit] = useStateBA(null);

  useEffectBA(() => {
    const h = () => setAccounts(window.BankAccountsStore.load());
    window.addEventListener("sss-bank-accounts-changed", h);
    window.addEventListener("sss-company-pay-changed", h);
    return () => { window.removeEventListener("sss-bank-accounts-changed", h); window.removeEventListener("sss-company-pay-changed", h); };
  }, []);

  const balances = window.CompanyCashStore ? window.CompanyCashStore.balances() : accounts.map(a => ({ ...a, balance: 0 }));
  const balOf = (id) => (balances.find(b => b.id === id) || {}).balance || 0;
  const coa = (window.SSSAccounting && window.SSSAccounting.ChartOfAccounts) || [];
  const coaOf = (code) => coa.find(c => c.code === code);

  const total = accounts.reduce((s, a) => s + balOf(a.id), 0);
  const cashTotal = accounts.filter(a => a.kind === "เงินสด").reduce((s, a) => s + balOf(a.id), 0);
  const bankTotal = accounts.filter(a => a.kind !== "เงินสด").reduce((s, a) => s + balOf(a.id), 0);

  const save = (acc) => {
    if (!acc.name.trim()) { window.toast && window.toast("กรอกชื่อบัญชี"); return; }
    if (!acc.code.trim()) { window.toast && window.toast("กรอกรหัสผังบัญชี (เช่น 1121)"); return; }
    const exists = accounts.some(a => a.id === acc.id);
    const next = exists ? accounts.map(a => a.id === acc.id ? acc : a) : [...accounts, acc];
    setAccounts(next);
    window.BankAccountsStore.save(next);
    window.logActivity && window.logActivity(exists ? "แก้ไขบัญชีธนาคาร" : "เพิ่มบัญชีธนาคาร", `${acc.name} · ผังบัญชี ${acc.code}`, "update");
    window.toast && window.toast(`${exists ? "บันทึก" : "เพิ่ม"}บัญชี ${acc.name} แล้ว`);
    setEdit(null);
  };

  const remove = async (acc) => {
    if (accounts.length <= 1) { window.toast && window.toast("ต้องมีอย่างน้อย 1 บัญชี"); return; }
    const ok = await window.confirmDelete(`บัญชี ${acc.name}`, `ผังบัญชี ${acc.code} · คงเหลือ ฿${fmt0(balOf(acc.id))}`);
    if (!ok) return;
    const next = accounts.filter(a => a.id !== acc.id);
    setAccounts(next);
    window.BankAccountsStore.save(next);
    window.toast && window.toast(`ลบบัญชี ${acc.name} แล้ว`);
  };

  return (
    <>
      <PageHead
        title="จัดการบัญชีธนาคาร"
        sub="บัญชีเงินสด-ธนาคารของบริษัท ใช้ในหน้าจ่ายเงิน · เบิกเงิน · เงินเดือน · รายรับรายจ่าย — เชื่อมกับผังบัญชีในระบบบัญชีและภาษี"
        right={<>
          <Btn icon={I.book} kind="ghost" onClick={() => navigate("accounting")}>ระบบบัญชีและภาษี</Btn>
          <Btn icon={I.plus} kind="primary" onClick={() => setEdit(baEmptyAcc())}>เพิ่มบัญชี</Btn>
        </>}
      />

      <div className="grid cols-4 mb-lg">
        <Stat label="จำนวนบัญชี" value={`${accounts.length} บัญชี`} sub={`เงินสด ${accounts.filter(a => a.kind === "เงินสด").length} · ธนาคาร ${accounts.filter(a => a.kind !== "เงินสด").length}`} icon={I.book} />
        <Stat label="เงินสดรวม" value={`฿${fmt0(cashTotal)}`} sub="ลิ้นชัก / ตู้เซฟ" icon={I.money} />
        <Stat label="เงินฝากธนาคารรวม" value={`฿${fmt0(bankTotal)}`} sub="ทุกบัญชีธนาคาร" icon={I.money} />
        <Stat label="รวมเงินทุกบัญชี" value={`฿${fmt0(total)}`} sub="ตรงกับหน้าบัญชีธนาคาร" icon={I.calc} />
      </div>

      <Card title="บัญชีทั้งหมด" sub="แต่ละบัญชีผูกกับรหัสผังบัญชี — ยอดคงเหลือคำนวณจากการรับ/จ่ายจริงในระบบ" flush>
        <div className="table-wrap">
          <table className="t">
            <thead><tr><th>บัญชี</th><th>ประเภท</th><th>เลขที่บัญชี / รายละเอียด</th><th>ผังบัญชี (เชื่อมบัญชี)</th><th className="right">ยอดคงเหลือ</th><th></th></tr></thead>
            <tbody>
              {accounts.map(a => {
                const c = coaOf(a.code);
                return (
                  <tr key={a.id}>
                    <td>
                      <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                        <span style={{ fontSize: 22 }}>{a.emoji}</span>
                        <div><div style={{ fontWeight: 600, fontSize: 13 }}>{a.name}</div><div style={{ fontSize: 11, color: "var(--ink-3)" }}>{a.short}</div></div>
                      </div>
                    </td>
                    <td><Badge tone={a.kind === "เงินสด" ? "warning" : "info"}>{a.kind}</Badge></td>
                    <td className="muted" style={{ fontSize: 12 }}>{a.detail || "—"}</td>
                    <td>
                      <button className="badge outline mono" style={{ cursor: "pointer" }} title="เปิดผังบัญชีในระบบบัญชี" onClick={() => navigate("accounting")}>{a.code}</button>
                      <div style={{ fontSize: 11, color: c ? "var(--ink-3)" : "var(--danger)", marginTop: 2 }}>{c ? c.name : "⚠ ไม่พบในผังบัญชี"}</div>
                    </td>
                    <td className="right amount" style={{ fontWeight: 600 }}>฿{fmt0(balOf(a.id))}</td>
                    <td>
                      <div style={{ display: "flex", gap: 4, justifyContent: "flex-end" }}>
                        <button className="icon-btn" title="แก้ไข" onClick={() => setEdit({ ...a })}><I.edit size={13} /></button>
                        <button className="icon-btn" title="ลบ" onClick={() => remove(a)}><I.trash size={13} /></button>
                      </div>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
        <div style={{ padding: "10px 14px", borderTop: "1px solid var(--line)", fontSize: 12, color: "var(--ink-3)", lineHeight: 1.7 }}>
          บัญชีเหล่านี้แสดงเป็นตัวเลือก "จ่ายจากบัญชี / รับเข้าบัญชี" ทั่วทั้งระบบ · รหัสผังบัญชีต้องตรงกับ <b style={{ color: "var(--ink-1)" }}>ผังบัญชี</b> ในระบบบัญชีและภาษี เพื่อให้ลงสมุดรายวันถูกบัญชี
        </div>
      </Card>

      {/* ผังบัญชีที่เกี่ยวข้อง (จากระบบบัญชี) */}
      <Card title="ผังบัญชีเงินสด-ธนาคาร (จากระบบบัญชีและภาษี)" sub="หมวดสินทรัพย์หมุนเวียน · ยอดยกมาในบัญชีแยกประเภท" className="mt-lg" flush
        right={<Btn size="sm" kind="ghost" icon={I.book} onClick={() => navigate("accounting")}>เปิดผังบัญชีทั้งหมด</Btn>}>
        <table className="t">
          <thead><tr><th>รหัส</th><th>ชื่อบัญชี</th><th>หมวด</th><th>ดุล</th><th className="right">ยอดในผังบัญชี</th><th>ผูกกับ</th></tr></thead>
          <tbody>
            {coa.filter(c => /^11(1|2)/.test(c.code)).map(c => {
              const linked = accounts.filter(a => a.code === c.code);
              return (
                <tr key={c.code}>
                  <td className="mono">{c.code}</td>
                  <td style={{ fontWeight: 500 }}>{c.name}</td>
                  <td className="muted" style={{ fontSize: 12 }}>{c.group}</td>
                  <td><Badge tone="outline">{c.normal}</Badge></td>
                  <td className="right amount">฿{fmt0(c.balance)}</td>
                  <td>{linked.length ? linked.map(a => <Badge key={a.id} tone="info">{a.emoji} {a.short}</Badge>) : <span className="muted" style={{ fontSize: 11.5 }}>ยังไม่ผูก</span>}</td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </Card>

      {/* Modal เพิ่ม/แก้ไข */}
      {edit && <BankAccountModal acc={edit} coa={coa} onClose={() => setEdit(null)} onSave={save} isNew={!accounts.some(a => a.id === edit.id)} />}
    </>
  );
}

function BankAccountModal({ acc, coa, onClose, onSave, isNew }) {
  const { Btn } = window.UI;
  const [f, setF] = useStateBA(acc);
  const upd = (k, v) => setF(p => ({ ...p, [k]: v }));
  const cashCoa = coa.filter(c => /^11(1|2)/.test(c.code));
  return (
    <>
      <div className="scrim" style={{ zIndex: 80 }} onClick={onClose}></div>
      <div style={{ position: "fixed", left: "50%", top: "50%", transform: "translate(-50%, -50%)", zIndex: 81, background: "var(--surface)", border: "1px solid var(--line)", borderRadius: 12, padding: 18, width: 480, maxWidth: "94vw", maxHeight: "92vh", overflowY: "auto", boxShadow: "var(--shadow-lg)" }}>
        <div style={{ fontSize: 14.5, fontWeight: 700, marginBottom: 12 }}>{isNew ? "เพิ่มบัญชีธนาคาร" : "แก้ไขบัญชี"}</div>
        <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
          <div className="field-row cols-2">
            <div className="field"><label>ประเภท</label>
              <div className="payseg" style={{ display: "flex" }}>
                {["เงินสด", "ธนาคาร"].map(k => (
                  <button key={k} type="button" className={"payseg-btn" + (f.kind === k ? " active" : "")} style={{ flex: 1 }} onClick={() => upd("kind", k) || upd("emoji", k === "เงินสด" ? "💵" : "🏦")}>{k === "เงินสด" ? "💵 เงินสด" : "🏦 ธนาคาร"}</button>
                ))}
              </div>
            </div>
            <div className="field"><label>ไอคอน</label>
              <input className="input" value={f.emoji} onChange={e => upd("emoji", e.target.value)} maxLength={2} style={{ textAlign: "center", fontSize: 18 }}></input>
            </div>
          </div>
          <div className="field"><label>ชื่อบัญชี *</label>
            <input className="input" value={f.name} onChange={e => upd("name", e.target.value)} placeholder="เช่น ธ.ไทยพาณิชย์ ออมทรัพย์" autoFocus></input>
          </div>
          <div className="field"><label>ชื่อย่อ (แสดงในตาราง)</label>
            <input className="input" value={f.short} onChange={e => upd("short", e.target.value)} placeholder="เช่น SCB"></input>
          </div>
          <div className="field"><label>เลขที่บัญชี / รายละเอียด</label>
            <input className="input" value={f.detail} onChange={e => upd("detail", e.target.value)} placeholder="เช่น 234-5-67890-1 · สาขาเซ็นทรัล"></input>
          </div>
          <div className="field"><label>ผูกกับผังบัญชี (รหัส) *</label>
            <select className="input" value={f.code} onChange={e => upd("code", e.target.value)}>
              <option value="">— เลือกรหัสผังบัญชี —</option>
              {cashCoa.map(c => <option key={c.code} value={c.code}>{c.code} · {c.name}</option>)}
            </select>
            <div style={{ fontSize: 11, color: "var(--ink-3)", marginTop: 4 }}>เลือกบัญชีในหมวดเงินสด-ธนาคารจากระบบบัญชี เพื่อให้ลงสมุดรายวันถูกต้อง</div>
          </div>
        </div>
        <div style={{ display: "flex", gap: 8, justifyContent: "flex-end", marginTop: 14 }}>
          <Btn kind="ghost" onClick={onClose}>ยกเลิก</Btn>
          <Btn kind="primary" icon={I.check} onClick={() => onSave(f)}>{isNew ? "เพิ่มบัญชี" : "บันทึก"}</Btn>
        </div>
      </div>
    </>
  );
}

window.BankAccountsPage = BankAccountsPage;
