/* global React, I, UI, SSSAccounting */
const { useState: useStateAR, useMemo: useMemoAR } = React;

// ============================================================
//  Posting Rules — configure doc-type → GL mapping
// ============================================================
function PostingRulesView() {
  const { Card, Btn, Badge, Switch } = window.UI;
  const A = window.SSSAccounting;
  const [rulesState, setRulesState] = useStateAR(A.PostingRules.map(r => ({...r})));

  const updateRule = (i, patch) => {
    setRulesState(rs => rs.map((r, j) => j === i ? { ...r, ...patch } : r));
    // mutate live data so JournalRoot also sees update
    Object.assign(A.PostingRules[i], patch);
  };

  return (
    <div style={{display: "flex", flexDirection: "column", gap: 14}}>
      <div style={{
        padding: "10px 14px", background: "var(--info-bg)", border: "1px solid var(--info)",
        borderRadius: "var(--radius-sm)", fontSize: 12, color: "var(--ink-2)",
        display: "flex", gap: 10, alignItems: "flex-start"
      }}>
        <I.shield size={14} stroke="var(--info)" style={{flexShrink: 0, marginTop: 2}}/>
        <div>
          <b>กฎการบันทึกอัตโนมัติ:</b> เมื่อมีเอกสารใหม่ ระบบจะใช้กฎเหล่านี้สร้าง JV เข้าสมุดรายวันให้อัตโนมัติ
          เปิด <b>Auto-post</b> เพื่อให้ระบบ post ทันทีโดยไม่ต้องตรวจสอบ หรือปิดไว้เพื่อรอ approve ก่อน
          การแก้ไขกฎจะมีผลกับเอกสารใหม่เท่านั้น (ไม่ย้อนหลัง)
        </div>
      </div>

      {rulesState.map((rule, i) => (
        <RuleCard key={rule.docType} rule={rule} index={i} onUpdate={(patch) => updateRule(i, patch)}/>
      ))}
    </div>
  );
}

function RuleCard({ rule, index, onUpdate }) {
  const { Btn, Badge, Switch } = window.UI;
  const A = window.SSSAccounting;
  const T = window.JOURNAL_TYPES[rule.journal];
  const Icon = I[rule.icon] || I.doc;
  const [editing, setEditing] = useStateAR(null); // line index being edited

  const saveLine = (i, acc) => {
    const nextLines = rule.lines.map((l, j) => j === i ? { ...l, acc } : l);
    onUpdate({ lines: nextLines });
    setEditing(null);
    window.toast && window.toast("บันทึกการแก้ไขบัญชีแล้ว");
  };

  return (
    <div style={{
      background: "var(--surface)",
      border: "1px solid var(--line)",
      borderRadius: "var(--radius)",
      overflow: "hidden",
      opacity: rule.enabled ? 1 : 0.6
    }}>
      <div style={{display: "flex", alignItems: "center", gap: 14, padding: "14px 16px", borderBottom: "1px solid var(--line)"}}>
        <div style={{
          width: 40, height: 40, borderRadius: 8,
          background: T.color, color: "var(--accent-ink)",
          display: "grid", placeItems: "center", flexShrink: 0
        }}><Icon size={18}/></div>
        <div style={{flex: 1}}>
          <div style={{display: "flex", alignItems: "center", gap: 8}}>
            <h3 style={{margin: 0, fontSize: 14}}>{rule.label}</h3>
            <span style={{
              fontSize: 10, padding: "2px 7px", borderRadius: 4,
              background: T.color, color: "var(--accent-ink)", fontWeight: 500
            }}>→ {T.label}</span>
          </div>
          <div style={{fontSize: 12, color: "var(--ink-3)", marginTop: 3}}>{rule.desc}</div>
        </div>

        <div style={{display: "flex", flexDirection: "column", gap: 6, alignItems: "flex-end"}}>
          <ToggleRow label="เปิดใช้งาน" value={rule.enabled} onChange={(v) => onUpdate({ enabled: v })}/>
          <ToggleRow label="Auto-post ทันที" value={rule.autoPost} onChange={(v) => onUpdate({ autoPost: v })} disabled={!rule.enabled}/>
        </div>
      </div>

      {/* Lines mapping */}
      <div style={{padding: "12px 16px", background: "var(--surface-2)"}}>
        <div style={{fontSize: 11, color: "var(--ink-3)", textTransform: "uppercase", letterSpacing: "0.04em", fontWeight: 500, marginBottom: 8}}>
          การ map บัญชี
        </div>
        <table style={{width: "100%", borderCollapse: "collapse", fontSize: 12.5}}>
          <thead>
            <tr>
              <th style={{...ruleTh, width: 60}}>ด้าน</th>
              <th style={{...ruleTh, width: 90}}>รหัส</th>
              <th style={ruleTh}>บัญชี</th>
              <th style={ruleTh}>คำนวณจาก</th>
              <th style={{...ruleTh, width: 70}}></th>
            </tr>
          </thead>
          <tbody>
            {rule.lines.map((l, i) => {
              const dynamic = l.acc?.startsWith("DYNAMIC_");
              const acc = dynamic ? null : A.accByCode[l.acc];
              return (
                <tr key={i} style={{borderTop: "1px solid var(--line)"}}>
                  <td style={ruleTd}>
                    <span style={{
                      fontSize: 11, padding: "2px 8px", borderRadius: 3, fontWeight: 600,
                      background: l.side === "Dr" ? "var(--info-bg)" : "var(--warning-bg)",
                      color: l.side === "Dr" ? "var(--info)" : "var(--warning)"
                    }}>{l.side}.</span>
                  </td>
                  <td style={{...ruleTd, fontFamily: "var(--font-mono)", fontSize: 11.5, color: "var(--ink-3)"}}>
                    {dynamic ? <Badge tone="info">DYN</Badge> : l.acc}
                  </td>
                  <td style={ruleTd}>
                    {editing === i && !dynamic ? (
                      <select className="input mono" defaultValue={l.acc} autoFocus
                        onChange={(e) => saveLine(i, e.target.value)}
                        onBlur={() => setEditing(null)}
                        style={{fontSize: 12, padding: "4px 6px", maxWidth: 240}}>
                        {A.ChartOfAccounts.map(a => <option key={a.code} value={a.code}>{a.code} · {a.name}</option>)}
                      </select>
                    ) : (
                      <>
                        <div style={{fontSize: 12.5}}>{acc?.name || l.note}</div>
                        {dynamic && <div style={{fontSize: 11, color: "var(--ink-4)", marginTop: 1}}>{l.note}</div>}
                      </>
                    )}
                  </td>
                  <td style={ruleTd}>
                    <span className="mono" style={{fontSize: 11, color: "var(--ink-2)",
                      background: "var(--surface)", padding: "2px 6px", borderRadius: 3,
                      border: "1px solid var(--line)"}}>{l.source}</span>
                    {l.optional && <span style={{fontSize: 10.5, color: "var(--ink-4)", marginLeft: 6}}>(optional)</span>}
                  </td>
                  <td style={{...ruleTd, textAlign: "right"}}>
                    <button title={dynamic ? "บัญชีแบบไดนามิก — แก้ไขไม่ได้" : "แก้ไขบัญชี"} disabled={dynamic}
                      onClick={() => !dynamic && setEditing(editing === i ? null : i)}
                      style={{background: "transparent", border: "none", cursor: dynamic ? "not-allowed" : "pointer", color: dynamic ? "var(--ink-4)" : "var(--ink-3)", padding: 4, opacity: dynamic ? 0.4 : 1}}>
                      <I.edit size={12}/>
                    </button>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

const ruleTh = { padding: "6px 10px", textAlign: "left", fontWeight: 500, color: "var(--ink-3)", fontSize: 10.5, textTransform: "uppercase", letterSpacing: "0.04em" };
const ruleTd = { padding: "8px 10px" };

function ToggleRow({ label, value, onChange, disabled }) {
  return (
    <label style={{
      display: "flex", alignItems: "center", gap: 8,
      fontSize: 12, color: disabled ? "var(--ink-4)" : "var(--ink-2)",
      cursor: disabled ? "not-allowed" : "pointer"
    }}>
      <span>{label}</span>
      <div onClick={() => !disabled && onChange(!value)} style={{
        width: 32, height: 18, borderRadius: 9,
        background: value && !disabled ? "var(--ink-1)" : "var(--surface-3)",
        position: "relative", transition: "all 0.15s",
        cursor: disabled ? "not-allowed" : "pointer"
      }}>
        <div style={{
          position: "absolute", top: 2, left: value ? 16 : 2,
          width: 14, height: 14, borderRadius: "50%",
          background: "var(--surface)", boxShadow: "0 1px 2px rgba(0,0,0,0.2)",
          transition: "all 0.15s"
        }}/>
      </div>
    </label>
  );
}

// ============================================================
//  Post History — list of recent postings linked to source docs
// ============================================================
function PostHistory() {
  const { Card, Btn, fmt0 } = window.UI;
  const A = window.SSSAccounting;
  const T = window.JOURNAL_TYPES;

  const exportLog = () => {
    const rows = A.JournalEntries.map(e => ({
      id: e.id, type: e.type, date: e.date, ref: e.ref, desc: e.desc, by: e.by || "ปิยะ ศ.",
      amount: e.lines.reduce((s, l) => s + l.dr, 0)
    }));
    window.exportRowsCSV("audit-log", [
      { key: "id", label: "เลขที่ JV" }, { key: "type", label: "ประเภท" }, { key: "date", label: "วันที่" },
      { key: "ref", label: "เอกสารอ้างอิง" }, { key: "desc", label: "คำอธิบาย" }, { key: "by", label: "ผู้บันทึก" }, { key: "amount", label: "ยอด" }
    ], rows);
  };

  // group by date
  const grouped = useMemoAR(() => {
    const g = {};
    A.JournalEntries.forEach(e => {
      if (!g[e.date]) g[e.date] = [];
      g[e.date].push(e);
    });
    return Object.entries(g).sort((a, b) => b[0].localeCompare(a[0]));
  }, []);

  return (
    <div style={{display: "flex", flexDirection: "column", gap: 14}}>
      <div style={{display: "flex", gap: 10, alignItems: "center"}}>
        <div style={{fontSize: 12, color: "var(--ink-3)"}}>
          แสดงการ post {A.JournalEntries.length} รายการ ในช่วง พ.ค. 2569
        </div>
        <div style={{flex: 1}}/>
        <Btn size="sm" kind="ghost" icon={I.download} onClick={exportLog}>ส่งออก audit log</Btn>
      </div>

      <Card flush>
        <table className="t">
          <thead>
            <tr>
              <th style={{width: 90}}>วันที่</th>
              <th style={{width: 80}}>ประเภท</th>
              <th style={{width: 120}}>เลขที่ JV</th>
              <th>เอกสารต้นทาง</th>
              <th>คำอธิบาย</th>
              <th>ผู้บันทึก</th>
              <th className="right" style={{width: 110}}>ยอด</th>
              <th style={{width: 80}}></th>
            </tr>
          </thead>
          <tbody>
            {grouped.map(([date, entries]) => entries.map((e, i) => {
              const dr = e.lines.reduce((s, l) => s + l.dr, 0);
              const type = T[e.type];
              return (
                <tr key={e.id}>
                  <td style={{fontSize: 12}}>{i === 0 ? date : ""}</td>
                  <td>
                    <span style={{
                      fontSize: 10.5, padding: "2px 7px", borderRadius: 4,
                      background: type.color, color: "var(--accent-ink)", fontWeight: 500
                    }}>{type.short}</span>
                  </td>
                  <td className="mono" style={{fontSize: 12, fontWeight: 600}}>{e.id}</td>
                  <td className="mono" style={{fontSize: 11.5, color: "var(--ink-2)"}}>
                    {e.ref.split("/").map((r, j) => (
                      <div key={j}>{r.trim()}</div>
                    ))}
                  </td>
                  <td style={{fontSize: 12.5}}>{e.desc}</td>
                  <td style={{fontSize: 12, color: "var(--ink-3)"}}>{e.by}</td>
                  <td className="right amount">฿{fmt0(dr)}</td>
                  <td>
                    <Btn size="sm" kind="ghost" onClick={() => window.toast && window.toast(`${e.id} · ${e.desc} — Dr ฿${fmt0(e.lines.reduce((s,l)=>s+l.dr,0))} = Cr ฿${fmt0(e.lines.reduce((s,l)=>s+l.cr,0))}`)}>ดู JV</Btn>
                  </td>
                </tr>
              );
            }))}
          </tbody>
        </table>
      </Card>
    </div>
  );
}

window.PostingRulesView = PostingRulesView;
window.PostHistory = PostHistory;
