/* Bonyan ERP — الحركات (Audit Log): من فعل ماذا ومتى، بالتفصيل.
   الرؤية للمدير فقط (صلاحية activity + RLS في القاعدة). */
const BNY_ACTIONS = {
  invoice_create:   { label: "تسجيل فاتورة", tone: "brand" },
  invoice_update:   { label: "تعديل فاتورة", tone: "warning" },
  invoice_delete:   { label: "حذف فاتورة", tone: "danger" },
  transfer:         { label: "نقل مخزني", tone: "brand" },
  material_add:     { label: "إضافة مادة", tone: "success" },
  material_update:  { label: "تعديل مادة", tone: "warning" },
  customer_add:     { label: "عميل جديد", tone: "success" },
  customer_edit:    { label: "تعديل عميل", tone: "warning" },
  supplier_add:     { label: "مورد جديد", tone: "success" },
  supplier_edit:    { label: "تعديل مورد", tone: "warning" },
  payment_in:       { label: "دفعة واردة", tone: "success" },
  payment_out:      { label: "دفعة صادرة", tone: "warning" },
  warehouse_add:    { label: "إضافة مخزن", tone: "success" },
  warehouse_edit:   { label: "تعديل مخزن", tone: "warning" },
  warehouse_delete: { label: "حذف مخزن", tone: "danger" },
  category_add:     { label: "إضافة فئة", tone: "success" },
  category_edit:    { label: "تعديل فئة", tone: "warning" },
  category_delete:  { label: "حذف فئة", tone: "danger" },
  user_save:        { label: "حفظ مستخدم", tone: "brand" },
  user_delete:      { label: "حذف مستخدم", tone: "danger" },
};

function ActivityScreen({ user }) {
  const I = window.BnyIcon;
  const D = window.BnyData;
  const { Card, Button, Input, Badge, Avatar } = window.BonyanDesignSystem_ad3ca0;
  const isMobile = window.useBnyMobile();
  const [rows, setRows] = React.useState(() => (D.activity || []).slice());
  const [loading, setLoading] = React.useState(false);
  const [q, setQ] = React.useState("");
  const [actF, setActF] = React.useState("all");

  const load = React.useCallback(async () => {
    if (!(window.BnyConfigured && window.BnyDB && window.BnyDB.fetchActivity)) { setRows((D.activity || []).slice()); return; }
    setLoading(true);
    try { setRows(await window.BnyDB.fetchActivity(300)); }
    catch (e) { console.warn("بُنيان: فشل جلب الحركات", e); setRows((D.activity || []).slice()); }
    finally { setLoading(false); }
  }, []);
  React.useEffect(() => { load(); }, [load]);

  if (!window.BnyCan(user, "activity")) {
    return (
      <div style={{ padding: "var(--space-8)" }}>
        <div className="bny-card" style={{ padding: 48, textAlign: "center", display: "flex", flexDirection: "column", alignItems: "center", gap: 14 }}>
          <span style={{ display: "inline-flex", alignItems: "center", justifyContent: "center", width: 64, height: 64, borderRadius: "var(--radius-lg)", background: "var(--danger-soft)", color: "var(--danger)" }}><I.alert size={32} /></span>
          <h2 style={{ fontSize: 20, margin: 0 }}>لا تملك صلاحية الوصول</h2>
          <p style={{ color: "var(--text-muted)", margin: 0 }}>سجل الحركات متاح للمدير فقط.</p>
        </div>
      </div>
    );
  }

  const fmtAt = (iso) => {
    try {
      const d = new Date(iso);
      return window.BnyDate(iso.slice(0, 10)) + " · " + String(d.getHours()).padStart(2, "0") + ":" + String(d.getMinutes()).padStart(2, "0");
    } catch (e) { return iso; }
  };
  const openRef = (r) => {
    if (r.ref && window.BnyInvoices && window.BnyInvoices.get(r.ref)) window.BnyOpenInvoice(r.ref);
  };
  const filtered = rows.filter((r) => {
    if (actF !== "all" && r.action !== actF) return false;
    if (q) { const t = (r.userName || "") + (r.details || "") + (r.ref || ""); if (!t.includes(q)) return false; }
    return true;
  });
  const usedActions = Array.from(new Set(rows.map((r) => r.action)));

  return (
    <div style={{ padding: isMobile ? "var(--space-5)" : "var(--space-8)", display: "flex", flexDirection: "column", gap: "var(--space-6)" }}>
      <Card title={"سجل الحركات (" + filtered.length + ")"}
        actions={<Button variant="secondary" size="sm" icon={<I.cloud size={15} />} onClick={load} disabled={loading}>{loading ? "جارٍ التحديث…" : "تحديث"}</Button>}>
        <div style={{ display: "flex", gap: 10, marginBottom: 14, flexWrap: "wrap", alignItems: "center" }}>
          <div style={{ flex: 1, minWidth: 200, maxWidth: 340 }}>
            <Input value={q} onChange={(e) => setQ(e.target.value)} placeholder="ابحث باسم المستخدم أو التفاصيل أو المرجع" icon={<I.search size={16} />} />
          </div>
          <select className="bny-input" value={actF} onChange={(e) => setActF(e.target.value)} style={{ width: 180, height: 40 }} aria-label="نوع الحركة">
            <option value="all">كل الحركات</option>
            {usedActions.map((a) => <option key={a} value={a}>{(BNY_ACTIONS[a] || {}).label || a}</option>)}
          </select>
        </div>

        <div style={{ display: "flex", flexDirection: "column" }}>
          {filtered.map((r, i) => {
            const meta = BNY_ACTIONS[r.action] || { label: r.action, tone: "neutral" };
            const clickable = !!(r.ref && window.BnyInvoices && window.BnyInvoices.get(r.ref));
            return (
              <div key={r.id || i} onClick={clickable ? () => openRef(r) : undefined}
                onMouseEnter={clickable ? (e) => (e.currentTarget.style.background = "var(--surface-hover)") : undefined}
                onMouseLeave={clickable ? (e) => (e.currentTarget.style.background = "transparent") : undefined}
                style={{ display: "flex", alignItems: "flex-start", gap: 12, padding: "12px 8px", margin: "0 -8px", borderRadius: "var(--radius-md)", borderTop: i > 0 ? "1px solid var(--border-subtle)" : "none", cursor: clickable ? "pointer" : "default", transition: "background var(--dur-fast,160ms) ease" }}>
                <Avatar name={r.userName || "؟"} size="sm" />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 8, flexWrap: "wrap" }}>
                    <span style={{ fontSize: 13.5, fontWeight: 700, color: "var(--text-strong)" }}>{r.userName || "غير معروف"}</span>
                    <span className={"bny-badge bny-badge--" + meta.tone}><span className="bny-badge__dot" />{meta.label}</span>
                    {r.ref && <span className="bny-tag" style={{ fontSize: 11, fontFamily: "var(--font-mono)" }}>{r.ref}</span>}
                  </div>
                  <div style={{ fontSize: 13, color: "var(--text-body)", marginTop: 3, lineHeight: 1.6 }}>{r.details}</div>
                </div>
                <div style={{ flex: "none", fontSize: 11.5, color: "var(--text-muted)", fontFamily: "var(--font-mono)", whiteSpace: "nowrap", textAlign: "end" }}>{fmtAt(r.at)}</div>
              </div>
            );
          })}
          {filtered.length === 0 && (
            <div style={{ padding: "36px 0", textAlign: "center", color: "var(--text-muted)", display: "flex", flexDirection: "column", alignItems: "center", gap: 8 }}>
              <span style={{ color: "var(--text-faint)" }}><I.history size={32} /></span>
              <div style={{ fontWeight: 600 }}>لا حركات مسجّلة بعد</div>
              <div style={{ fontSize: 12.5 }}>كل فاتورة أو نقل مخزني أو إضافة مادة ستظهر هنا تلقائيًا مع اسم من قام بها.</div>
            </div>
          )}
        </div>
      </Card>
    </div>
  );
}
window.ActivityScreen = ActivityScreen;
