/* global React, I, UI, SSSAccounting */
const { useState: useStateN, useMemo: useMemoN, useEffect: useEffectN } = React;

// ============================================================
//  บันทึกรายการสมุดรายวันใหม่ (New Journal Entry)
//  Validates Dr = Cr per double-entry rule
// ============================================================
function NewJournalDrawer({ open, onClose }) {
  const { Drawer, Btn, Badge } = window.UI;
  const A = window.SSSAccounting;
  const today = "23/05/2569";

  const [jtype, setJtype] = useStateN("GJ");
  const [date, setDate] = useStateN(today);
  const [ref, setRef] = useStateN("");
  const [desc, setDesc] = useStateN("");
  const [lines, setLines] = useStateN([
    { acc: "", dr: "", cr: "", note: "" },
    { acc: "", dr: "", cr: "", note: "" }
  ]);

  useEffectN(() => {
    if (open) {
      // suggest next JV number per type
      const prefix = jtype + "69-";
      const same = A.JournalEntries.filter(e => e.type === jtype);
      const maxN = Math.max(0, ...same.map(e => parseInt(e.id.split("-")[1]) || 0));
      // not really used in UI but helpful
    }
  }, [open, jtype]);

  const totDr = lines.reduce((s, l) => s + (parseFloat(l.dr) || 0), 0);
  const totCr = lines.reduce((s, l) => s + (parseFloat(l.cr) || 0), 0);
  const diff = totDr - totCr;
  const balanced = Math.abs(diff) < 0.005 && totDr > 0;

  const nextId = useMemoN(() => {
    const same = A.JournalEntries.filter(e => e.type === jtype);
    const maxN = Math.max(0, ...same.map(e => parseInt(e.id.split("-")[1]) || 0));
    return `${jtype}69-${String(maxN + 1).padStart(4, "0")}`;
  }, [jtype]);

  const updateLine = (i, field, val) => {
    setLines(ls => ls.map((l, j) => j === i ? { ...l, [field]: val } : l));
  };
  const addLine = () => setLines(ls => [...ls, { acc: "", dr: "", cr: "", note: "" }]);
  const removeLine = (i) => setLines(ls => ls.length > 2 ? ls.filter((_, j) => j !== i) : ls);

  const save = () => {
    if (!balanced) return;
    A.JournalEntries.unshift({
      id: nextId,
      type: jtype,
      date,
      by: "ปิยะ ศ.",
      ref: ref || "—",
      desc: desc || T[jtype]?.label || "บันทึกรายการ",
      lines: lines
        .filter(l => l.acc && ((parseFloat(l.dr) || 0) > 0 || (parseFloat(l.cr) || 0) > 0))
        .map(l => ({ acc: l.acc, dr: parseFloat(l.dr) || 0, cr: parseFloat(l.cr) || 0, note: l.note || "" }))
    });
    window.logActivity && window.logActivity("บันทึกสมุดรายวัน", `${nextId} — Dr ฿${totDr.toLocaleString()}`, "create");
    window.toast && window.toast(`บันทึก ${nextId} เรียบร้อย — Dr ฿${totDr.toLocaleString()} = Cr ฿${totCr.toLocaleString()}`);
    onClose();
    // reset
    setLines([{ acc: "", dr: "", cr: "", note: "" }, { acc: "", dr: "", cr: "", note: "" }]);
    setRef(""); setDesc("");
  };

  const T = window.JOURNAL_TYPES || {
    GJ: { label: "สมุดรายวันทั่วไป", short: "ทั่วไป", color: "var(--ink-1)" },
    SJ: { label: "สมุดรายวันขาย", short: "ขาย", color: "oklch(60% 0.10 150)" },
    PJ: { label: "สมุดรายวันซื้อ", short: "ซื้อ", color: "oklch(55% 0.10 230)" },
    CR: { label: "สมุดรายวันรับเงิน", short: "รับเงิน", color: "oklch(60% 0.10 150)" },
    CP: { label: "สมุดรายวันจ่ายเงิน", short: "จ่ายเงิน", color: "oklch(58% 0.18 25)" }
  };

  return (
    <Drawer
      open={open}
      onClose={onClose}
      title="บันทึกสมุดรายวันใหม่"
      wide
      footer={
        <>
          <div style={{flex: 1, fontSize: 12, color: balanced ? "var(--success)" : "var(--warning)"}}>
            {balanced
              ? <><I.check size={12}/> สมดุล: Dr = Cr</>
              : totDr === 0 && totCr === 0
                ? "กรุณากรอกจำนวนเงิน"
                : `ไม่สมดุล: ผลต่าง ฿${Math.abs(diff).toLocaleString("th-TH", {minimumFractionDigits: 2, maximumFractionDigits: 2})}`}
          </div>
          <Btn kind="ghost" onClick={onClose}>ยกเลิก</Btn>
          <Btn kind="primary" onClick={save} disabled={!balanced}>บันทึกรายการ</Btn>
        </>
      }>

      {/* Type selector */}
      <Field label="ประเภทสมุดรายวัน">
        <div style={{display: "grid", gridTemplateColumns: "repeat(5, 1fr)", gap: 6}}>
          {Object.entries(T).map(([k, v]) => (
            <button key={k} onClick={() => setJtype(k)} style={{
              padding: "8px 6px", borderRadius: 6,
              background: jtype === k ? "var(--ink-1)" : "var(--surface)",
              color: jtype === k ? "var(--accent-ink)" : "var(--ink-2)",
              border: `1px solid ${jtype === k ? "var(--ink-1)" : "var(--line)"}`,
              fontSize: 12, cursor: "pointer", fontFamily: "var(--font)"
            }}>{v.short}</button>
          ))}
        </div>
      </Field>

      {/* Meta */}
      <div style={{display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10}}>
        <Field label="วันที่ลงรายการ"><Input value={date} onChange={setDate}/></Field>
        <Field label="เลขที่ JV (อัตโนมัติ)">
          <Input value={nextId} readOnly mono/>
        </Field>
      </div>
      <Field label="เลขที่เอกสารอ้างอิง" hint="เช่น INV-2569-0205, PV-2569-0072">
        <Input value={ref} onChange={setRef} placeholder="ใส่เลขที่เอกสาร"/>
      </Field>
      <Field label="คำอธิบายรายการ" hint="ระบุเหตุการณ์ทางบัญชีโดยย่อ">
        <Input value={desc} onChange={setDesc} placeholder="เช่น ขายเชื่อ บจก. ..."/>
      </Field>

      {/* Lines table */}
      <div style={{marginTop: 18, marginBottom: 10, display: "flex", justifyContent: "space-between", alignItems: "center"}}>
        <div style={{fontSize: 13, fontWeight: 600}}>รายการเดบิต/เครดิต</div>
        <button onClick={addLine} style={{
          fontSize: 12, padding: "4px 10px", borderRadius: 4,
          background: "transparent", border: "1px solid var(--line)",
          cursor: "pointer", color: "var(--ink-2)", fontFamily: "var(--font)",
          display: "inline-flex", alignItems: "center", gap: 4
        }}><I.plus size={11}/> เพิ่มบรรทัด</button>
      </div>

      <div style={{
        border: "1px solid var(--line)", borderRadius: "var(--radius-sm)",
        overflow: "hidden"
      }}>
        <table style={{width: "100%", borderCollapse: "collapse", fontSize: 12.5}}>
          <thead>
            <tr style={{background: "var(--surface-2)"}}>
              <th style={{padding: "8px 8px", textAlign: "left", fontWeight: 500, color: "var(--ink-3)", fontSize: 11, textTransform: "uppercase", letterSpacing: "0.04em"}}>บัญชี</th>
              <th style={{padding: "8px 8px", textAlign: "right", fontWeight: 500, color: "var(--ink-3)", fontSize: 11, width: 110}}>เดบิต</th>
              <th style={{padding: "8px 8px", textAlign: "right", fontWeight: 500, color: "var(--ink-3)", fontSize: 11, width: 110}}>เครดิต</th>
              <th style={{width: 28}}></th>
            </tr>
          </thead>
          <tbody>
            {lines.map((l, i) => (
              <tr key={i} style={{borderTop: "1px solid var(--line-soft)"}}>
                <td style={{padding: 6}}>
                  <AccountPicker value={l.acc} onChange={v => updateLine(i, "acc", v)}/>
                  <input value={l.note} onChange={e => updateLine(i, "note", e.target.value)} placeholder="บันทึกเสริม (ไม่บังคับ)"
                    style={{...inputStyle, marginTop: 4, fontSize: 11.5, padding: "5px 7px"}}/>
                </td>
                <td style={{padding: 6}}>
                  <input type="number" value={l.dr} onChange={e => updateLine(i, "dr", e.target.value)} placeholder="0.00"
                    style={{...inputStyle, textAlign: "right", fontVariantNumeric: "tabular-nums",
                      background: l.dr ? "var(--surface-2)" : "var(--surface)"}}/>
                </td>
                <td style={{padding: 6}}>
                  <input type="number" value={l.cr} onChange={e => updateLine(i, "cr", e.target.value)} placeholder="0.00"
                    style={{...inputStyle, textAlign: "right", fontVariantNumeric: "tabular-nums",
                      background: l.cr ? "var(--surface-2)" : "var(--surface)"}}/>
                </td>
                <td style={{textAlign: "center"}}>
                  {lines.length > 2 && (
                    <button onClick={() => removeLine(i)} style={{
                      background: "transparent", border: "none", cursor: "pointer",
                      color: "var(--ink-4)", padding: 4
                    }}><I.close size={12}/></button>
                  )}
                </td>
              </tr>
            ))}
          </tbody>
          <tfoot>
            <tr style={{borderTop: "2px solid var(--ink-1)", background: "var(--surface-2)", fontWeight: 600}}>
              <td style={{padding: "10px 8px"}}>รวม</td>
              <td style={{padding: "10px 8px", textAlign: "right", fontVariantNumeric: "tabular-nums"}}>
                ฿{totDr.toLocaleString("th-TH", {minimumFractionDigits: 2, maximumFractionDigits: 2})}
              </td>
              <td style={{padding: "10px 8px", textAlign: "right", fontVariantNumeric: "tabular-nums"}}>
                ฿{totCr.toLocaleString("th-TH", {minimumFractionDigits: 2, maximumFractionDigits: 2})}
              </td>
              <td></td>
            </tr>
            {totDr > 0 && (
              <tr style={{background: balanced ? "var(--success-bg)" : "var(--warning-bg)"}}>
                <td colSpan="4" style={{padding: "8px 8px", textAlign: "center", fontSize: 11.5, color: balanced ? "var(--success)" : "var(--warning)"}}>
                  {balanced
                    ? <><I.check size={11}/> รายการสมดุล Dr = Cr ตามหลักบัญชีคู่</>
                    : `ไม่สมดุล ผลต่าง ฿${Math.abs(diff).toLocaleString("th-TH", {minimumFractionDigits: 2, maximumFractionDigits: 2})} ${diff > 0 ? "(Dr มากกว่า Cr)" : "(Cr มากกว่า Dr)"}`}
                </td>
              </tr>
            )}
          </tfoot>
        </table>
      </div>

      <div style={{marginTop: 12, padding: "10px 12px", background: "var(--surface-2)", borderRadius: "var(--radius-sm)", fontSize: 11.5, color: "var(--ink-3)"}}>
        💡 <b style={{color: "var(--ink-2)"}}>หลักบัญชีคู่ (Double-entry):</b> ทุกรายการต้องมีผลรวมเดบิต = เครดิต
        ระบบจะไม่อนุญาตให้บันทึกหากยอดไม่สมดุล
      </div>
    </Drawer>
  );
}

const inputStyle = {
  width: "100%",
  padding: "7px 9px",
  border: "1px solid var(--line)",
  borderRadius: 4,
  background: "var(--surface)",
  color: "var(--ink-1)",
  fontSize: 12.5,
  fontFamily: "var(--font)",
  outline: "none",
  boxSizing: "border-box"
};

function Field({ label, hint, children }) {
  return (
    <div style={{marginBottom: 12}}>
      <label style={{display: "block", fontSize: 11, color: "var(--ink-3)", marginBottom: 4, textTransform: "uppercase", letterSpacing: "0.04em", fontWeight: 500}}>
        {label}
        {hint && <span style={{fontWeight: 400, textTransform: "none", letterSpacing: 0, marginLeft: 8, color: "var(--ink-4)"}}>· {hint}</span>}
      </label>
      {children}
    </div>
  );
}

function Input({ value, onChange, placeholder, readOnly, mono }) {
  return (
    <input
      value={value}
      onChange={e => onChange && onChange(e.target.value)}
      placeholder={placeholder}
      readOnly={readOnly}
      style={{
        ...inputStyle,
        fontFamily: mono ? "var(--font-mono)" : inputStyle.fontFamily,
        background: readOnly ? "var(--surface-2)" : inputStyle.background,
        color: readOnly ? "var(--ink-3)" : inputStyle.color
      }}
    />
  );
}

function AccountPicker({ value, onChange }) {
  const A = window.SSSAccounting;
  const [open, setOpen] = useStateN(false);
  const [q, setQ] = useStateN("");
  const acc = A.accByCode[value];

  const filtered = A.ChartOfAccounts.filter(a => {
    if (!q) return true;
    return a.code.includes(q) || a.name.toLowerCase().includes(q.toLowerCase());
  });

  return (
    <div style={{position: "relative"}}>
      <button onClick={() => setOpen(o => !o)} style={{
        ...inputStyle,
        textAlign: "left", cursor: "pointer",
        display: "flex", alignItems: "center", gap: 6
      }}>
        {acc ? <>
          <span className="mono" style={{color: "var(--ink-3)"}}>{acc.code}</span>
          <span style={{flex: 1, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap"}}>{acc.name}</span>
        </> : <span style={{color: "var(--ink-4)"}}>เลือกบัญชี…</span>}
        <I.chevronDown size={12} stroke="var(--ink-3)"/>
      </button>
      {open && (
        <>
          <div onClick={() => setOpen(false)} style={{position: "fixed", inset: 0, zIndex: 30}}/>
          <div style={{
            position: "absolute", top: "calc(100% + 4px)", left: 0, right: 0,
            zIndex: 31,
            background: "var(--surface)",
            border: "1px solid var(--line-strong)",
            borderRadius: "var(--radius-sm)",
            boxShadow: "var(--shadow-lg)",
            maxHeight: 320, overflowY: "auto"
          }}>
            <div style={{padding: 6, borderBottom: "1px solid var(--line)", position: "sticky", top: 0, background: "var(--surface)"}}>
              <input autoFocus value={q} onChange={e => setQ(e.target.value)} placeholder="ค้นหารหัส/ชื่อบัญชี…"
                style={{...inputStyle, fontSize: 12}}/>
            </div>
            {filtered.map(a => (
              <div key={a.code} onClick={() => { onChange(a.code); setOpen(false); setQ(""); }}
                style={{padding: "7px 10px", cursor: "pointer", borderBottom: "1px solid var(--line-soft)",
                  display: "flex", gap: 8, alignItems: "center"}}
                onMouseOver={e => e.currentTarget.style.background = "var(--surface-2)"}
                onMouseOut={e => e.currentTarget.style.background = "transparent"}>
                <span className="mono" style={{fontSize: 11.5, color: "var(--ink-3)", minWidth: 36}}>{a.code}</span>
                <span style={{flex: 1, fontSize: 12}}>{a.name}</span>
                <span style={{fontSize: 10, color: "var(--ink-4)"}}>{a.type}</span>
              </div>
            ))}
            {filtered.length === 0 && <div style={{padding: 14, textAlign: "center", color: "var(--ink-4)", fontSize: 12}}>ไม่พบบัญชี</div>}
          </div>
        </>
      )}
    </div>
  );
}

window.NewJournalDrawer = NewJournalDrawer;
