// ==========================================
// Audit Log — who did what, when
// Reads from Supabase audit_logs table.
// ==========================================

function AuditPage({ state }) {
  const [logs, setLogs] = useState([]);
  const [loading, setLoading] = useState(true);
  const [typeFilter, setTypeFilter] = useState("all");
  const [actionFilter, setActionFilter] = useState("all");
  const [userFilter, setUserFilter] = useState("");
  const [limit, setLimit] = useState(200);

  const cloudMode = !!window.SUPA;

  useEffect(() => {
    if (!cloudMode) { setLoading(false); return; }
    refresh();
  }, [limit]);

  async function refresh() {
    setLoading(true);
    try {
      const data = await window.DB.fetchAuditLogs({ limit });
      setLogs(data);
    } finally { setLoading(false); }
  }

  const rows = logs
    .filter((r) => typeFilter === "all" || r.entity_type === typeFilter)
    .filter((r) => actionFilter === "all" || r.action === actionFilter)
    .filter((r) => !userFilter || (r.username || "").toLowerCase().includes(userFilter.toLowerCase()));

  const matMap = Object.fromEntries((state.materials || []).map((m) => [m.id, m]));
  const projMap = Object.fromEntries((state.projects || []).map((p) => [p.id, p]));

  return (
    <div className="page">
      <div className="page-head">
        <div>
          <h1>📜 บันทึกการแก้ไข (Audit Log)</h1>
          <p className="muted">ดูประวัติการเพิ่ม/แก้/ลบ ทั้งหมดในระบบ — ใคร · ทำอะไร · เมื่อไหร่</p>
        </div>
        <button className="btn-primary" onClick={refresh} disabled={loading}>
          {loading ? "กำลังโหลด..." : "↻ รีเฟรช"}
        </button>
      </div>

      {!cloudMode && (
        <div className="alert-banner alert-warn">
          <span>⚠ Audit log ใช้งานในโหมด Cloud เท่านั้น — โปรดเชื่อมต่อ Supabase ก่อน</span>
        </div>
      )}

      <div className="filter-bar">
        <div className="chip-group">
          <button className={`chip ${typeFilter === "all" ? "active" : ""}`} onClick={() => setTypeFilter("all")}>ทั้งหมด</button>
          <button className={`chip ${typeFilter === "project" ? "active" : ""}`} onClick={() => setTypeFilter("project")}>🏢 หน่วยงาน</button>
          <button className={`chip ${typeFilter === "material" ? "active" : ""}`} onClick={() => setTypeFilter("material")}>🧰 วัสดุ</button>
          <button className={`chip ${typeFilter === "transaction" ? "active" : ""}`} onClick={() => setTypeFilter("transaction")}>💱 ธุรกรรม</button>
        </div>
        <div className="filter-right">
          <select value={actionFilter} onChange={(e) => setActionFilter(e.target.value)}>
            <option value="all">ทุกการกระทำ</option>
            <option value="create">➕ เพิ่ม</option>
            <option value="update">✎ แก้ไข</option>
            <option value="delete">🗑 ลบ</option>
          </select>
          <input placeholder="ค้นหาผู้ใช้..." value={userFilter} onChange={(e) => setUserFilter(e.target.value)} />
        </div>
      </div>

      <div className="card no-pad">
        <div className="table-wrap">
          <table className="data-table">
            <thead>
              <tr>
                <th style={{ width: "150px" }}>เวลา</th>
                <th style={{ width: "120px" }}>ผู้ใช้</th>
                <th style={{ width: "100px" }}>การกระทำ</th>
                <th style={{ width: "120px" }}>ประเภท</th>
                <th>รายการ</th>
                <th>การเปลี่ยนแปลง</th>
              </tr>
            </thead>
            <tbody>
              {loading && <tr><td colSpan="6" style={{ textAlign: "center", padding: 24 }}>กำลังโหลด...</td></tr>}
              {!loading && rows.length === 0 && (
                <tr><td colSpan="6"><Empty /></td></tr>
              )}
              {!loading && rows.map((r) => (
                <tr key={r.id}>
                  <td className="mono small">{fmtDate(r.timestamp)}</td>
                  <td><b>{r.username || "—"}</b></td>
                  <td><AuditActionPill action={r.action} /></td>
                  <td><AuditTypePill type={r.entity_type} /></td>
                  <td>
                    <b>{r.entity_name || r.entity_id || "—"}</b>
                    <div className="muted small mono">{r.entity_id}</div>
                  </td>
                  <td className="small">
                    <ChangesDisplay
                      action={r.action}
                      changes={r.changes}
                      matMap={matMap}
                      projMap={projMap}
                    />
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {!loading && rows.length >= limit && (
        <div style={{ textAlign: "center", marginTop: 14 }}>
          <button className="btn-ghost" onClick={() => setLimit(limit + 200)}>
            โหลดเพิ่มอีก 200 รายการ
          </button>
        </div>
      )}

      {!loading && logs.length > 0 && (
        <div className="muted small" style={{ marginTop: 12, textAlign: "right" }}>
          แสดง {rows.length} / {logs.length} รายการ
        </div>
      )}
    </div>
  );
}

// ---------- Sub-components ----------
function AuditActionPill({ action }) {
  const map = {
    create: { bg: "#d1fae5", color: "#065f46", icon: "➕", label: "เพิ่ม" },
    update: { bg: "#dbeafe", color: "#1e40af", icon: "✎",  label: "แก้ไข" },
    delete: { bg: "#fee2e2", color: "#991b1b", icon: "🗑", label: "ลบ" },
  };
  const m = map[action] || { bg: "#f1f5f9", color: "#475569", icon: "?", label: action };
  return <span className="status-pill" style={{ background: m.bg, color: m.color }}>{m.icon} {m.label}</span>;
}

function AuditTypePill({ type }) {
  const map = {
    project:     { icon: "🏢", label: "หน่วยงาน",  bg: "#fef3c7", color: "#92400e" },
    material:    { icon: "🧰", label: "วัสดุ",     bg: "#e0e7ff", color: "#3730a3" },
    transaction: { icon: "💱", label: "ธุรกรรม",   bg: "#fae8ff", color: "#86198f" },
  };
  const m = map[type] || { icon: "?", label: type, bg: "#f1f5f9", color: "#475569" };
  return <span className="status-pill" style={{ background: m.bg, color: m.color }}>{m.icon} {m.label}</span>;
}

function ChangesDisplay({ action, changes, matMap, projMap }) {
  if (!changes) return <span className="muted">—</span>;
  if (action === "create" || action === "delete") {
    // Show snapshot of key fields
    const items = [];
    if (changes.code)       items.push(`รหัส: ${changes.code}`);
    if (changes.name)       items.push(`ชื่อ: ${changes.name}`);
    if (changes.category)   items.push(`หมวด: ${changes.category}`);
    if (changes.qty != null && changes.type) {
      const matName = matMap[changes.id]?.name || changes.id || "";
      items.push(`${changes.type === "receive" ? "📥" : changes.type === "issue" ? "📤" : "🔄"} ${changes.qty}`);
    }
    if (changes.projectId)  items.push(`→ ${projMap[changes.projectId]?.code || changes.projectId}`);
    if (changes.fromProjectId && changes.toProjectId) {
      items.push(`${projMap[changes.fromProjectId]?.code || "?"} → ${projMap[changes.toProjectId]?.code || "?"}`);
    }
    return <span>{items.join(" · ") || "—"}</span>;
  }
  if (action === "update" && typeof changes === "object") {
    // Field-level diff: { fieldA: { from, to }, ... }
    const entries = Object.entries(changes).filter(([k, v]) => v && typeof v === "object" && "from" in v);
    if (entries.length === 0) return <span className="muted">—</span>;
    return (
      <div>
        {entries.slice(0, 4).map(([k, v]) => (
          <div key={k} className="audit-change-line">
            <b>{k}</b>: <span style={{ color: "#ef4444" }}>{fmtVal(v.from)}</span> → <span style={{ color: "#10b981" }}>{fmtVal(v.to)}</span>
          </div>
        ))}
        {entries.length > 4 && <div className="muted">…และอีก {entries.length - 4} field</div>}
      </div>
    );
  }
  return <span className="muted">—</span>;
}

function fmtVal(v) {
  if (v === null || v === undefined || v === "") return "—";
  if (typeof v === "object") return JSON.stringify(v);
  return String(v).slice(0, 50);
}
