/* =========================================================
   Operations — routed-action oversight (Phase J)
   =========================================================
   "1,500 calls today -> what are the expected actions, and how were
   they communicated?" Read-only dashboard over the action-routing layer:
     - metric tiles (total / queued / dispatched / needs-review / overdue)
     - an urgency breakdown (critical / high / normal / low)
     - a by-department breakdown with SLA targets + share bars
     - the needs-approval strip + routed-actions table + CSV export
   Data: GET /action-routing/ops/summary + /actions + /departments
   (all tenant-scoped, in routers/action_routing.py).
   ========================================================= */

const ActionOpsTile = ({ k, v, tone, sub }) => (
  <div className="card card-pad" style={{ padding: 16 }}>
    <div style={{ fontSize: 11.5, textTransform: "uppercase", letterSpacing: ".08em", color: "var(--fg-muted)", fontWeight: 600, marginBottom: 8 }}>{k}</div>
    <div className="num" style={{ fontSize: 26, color:
      tone === "danger" ? "var(--mk-danger)" : tone === "warn" ? "var(--mk-warning)" : tone === "success" ? "var(--mk-success)" : "var(--fg)" }}>{v}</div>
    {sub && <div style={{ fontSize: 12, color: "var(--fg-muted)", marginTop: 4 }}>{sub}</div>}
  </div>
);

const URGENCY_TONE = { critical: "var(--mk-danger)", high: "var(--mk-warning)", normal: "var(--fg)", low: "var(--fg-muted)" };
const URGENCY_ORDER = ["critical", "high", "normal", "low"];

const UrgencyChip = ({ tier, count }) => (
  <div className="card" style={{ padding: "10px 14px", display: "flex", alignItems: "center", gap: 10, borderLeft: `3px solid ${URGENCY_TONE[tier] || "var(--fg)"}` }}>
    <span className="num" style={{ fontSize: 20, color: URGENCY_TONE[tier] || "var(--fg)" }}>{count}</span>
    <span style={{ fontSize: 12.5, textTransform: "capitalize", color: "var(--fg-muted)" }}>{tier}</span>
  </div>
);

const OperationsDashboard = ({ onGo }) => {
  const [summary, setSummary] = React.useState(null);
  const [rows, setRows] = React.useState([]);
  const [depts, setDepts] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [err, setErr] = React.useState(null);

  React.useEffect(() => {
    let live = true;
    (async () => {
      try {
        const [s, a, d] = await Promise.all([
          apiRequest("/action-routing/ops/summary"),
          apiRequest("/action-routing/actions"),
          apiRequest("/action-routing/departments").catch(() => []),
        ]);
        if (!live) return;
        setSummary(s || {});
        setRows(Array.isArray(a) ? a : []);
        setDepts(Array.isArray(d) ? d : []);
      } catch (e) {
        if (live) setErr(String((e && e.message) || e));
      } finally {
        if (live) setLoading(false);
      }
    })();
    return () => { live = false; };
  }, []);

  if (loading) return <div className="card card-pad">Loading operations…</div>;
  if (err) return <div className="card card-pad" style={{ color: "var(--mk-danger)" }}>Couldn’t load operations: {err}</div>;

  const byStatus = (summary && summary.by_dispatch_status) || {};
  const byUrgency = (summary && summary.by_urgency) || {};
  const byDept = (summary && summary.by_department) || {};
  const total = summary?.total ?? 0;
  const n = (k) => byStatus[k] || 0;
  const awaiting = rows.filter((r) => String(r.policy_basis || "").includes("mode=human_review"));
  const overdue = rows.filter((r) => r.sla_due_at && new Date(r.sla_due_at) < new Date() && !["dispatched", "resolved"].includes(r.dispatch_status));

  // by-department breakdown: map department ids -> names/SLA, include an "Unrouted" remainder.
  const deptList = (depts || []).map((d) => ({ id: d.id, name: d.name, sla: d.sla_hours, count: byDept[d.id] || 0 }));
  const routedSum = deptList.reduce((acc, d) => acc + d.count, 0);
  const unrouted = Math.max(0, total - routedSum);
  const deptRows = deptList.concat(unrouted > 0 ? [{ id: "_unrouted", name: "Unrouted (no rule matched)", sla: null, count: unrouted, muted: true }] : []);
  deptRows.sort((a, b) => b.count - a.count);
  const maxCount = Math.max(1, ...deptRows.map((d) => d.count));

  const exportCsv = () => {
    try { window.open(`${API_PREFIX}/action-routing/reports/actions.csv`, "_blank"); }
    catch (e) { /* no-op */ }
  };

  return (
    <div className="stack" style={{ gap: 20 }}>
      <div className="row between">
        <h2 style={{ margin: 0 }}>Operations</h2>
        <div className="row" style={{ gap: 12, alignItems: "center" }}>
          <span style={{ fontSize: 13, color: "var(--fg-muted)" }}>Routed actions from your calls</span>
          <button className="btn btn-ghost" style={{ fontSize: 12.5 }} onClick={exportCsv}>Export CSV</button>
        </div>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(150px, 1fr))", gap: 12 }}>
        <ActionOpsTile k="Total actions" v={total} />
        <ActionOpsTile k="Queued" v={n("queued")} />
        <ActionOpsTile k="Dispatched" v={n("dispatched")} tone="success" />
        <ActionOpsTile k="Needs review" v={awaiting.length} tone={awaiting.length ? "danger" : undefined} sub="never auto-sent" />
        <ActionOpsTile k="Overdue SLA" v={overdue.length} tone={overdue.length ? "warn" : undefined} />
      </div>

      {/* Urgency breakdown */}
      <div className="card card-pad">
        <div style={{ fontWeight: 600, marginBottom: 10 }}>By urgency</div>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(110px, 1fr))", gap: 10 }}>
          {URGENCY_ORDER.map((t) => <UrgencyChip key={t} tier={t} count={byUrgency[t] || 0} />)}
        </div>
      </div>

      {/* By-department breakdown with SLA target + share bars */}
      <div className="card card-pad">
        <div className="row between" style={{ marginBottom: 10 }}>
          <div style={{ fontWeight: 600 }}>By department</div>
          <div style={{ fontSize: 12, color: "var(--fg-muted)" }}>{deptList.length} departments · SLA target</div>
        </div>
        {deptRows.length === 0 ? (
          <div style={{ fontSize: 13, color: "var(--fg-muted)" }}>No departments configured yet. Add departments + routing rules to direct actions to the right teams.</div>
        ) : (
          <div className="stack" style={{ gap: 8 }}>
            {deptRows.map((d) => (
              <div key={d.id} style={{ display: "grid", gridTemplateColumns: "minmax(140px, 1.4fr) 64px 1fr 48px", gap: 12, alignItems: "center", fontSize: 13 }}>
                <div style={{ color: d.muted ? "var(--fg-muted)" : "var(--fg)", fontWeight: d.muted ? 400 : 500 }}>{d.name}</div>
                <div style={{ fontSize: 12, color: "var(--fg-muted)" }}>{d.sla != null ? `${d.sla}h` : "—"}</div>
                <div style={{ height: 8, background: "var(--border, rgba(0,0,0,.08))", borderRadius: 6, overflow: "hidden" }}>
                  <div style={{ width: `${Math.round((d.count / maxCount) * 100)}%`, height: "100%", background: d.muted ? "var(--fg-muted)" : "var(--mk-accent, var(--fg))", opacity: d.muted ? 0.4 : 0.85 }} />
                </div>
                <div className="num" style={{ textAlign: "right", color: d.muted ? "var(--fg-muted)" : "var(--fg)" }}>{d.count}</div>
              </div>
            ))}
          </div>
        )}
      </div>

      {awaiting.length > 0 && (
        <div className="card card-pad" style={{ borderLeft: "3px solid var(--mk-danger)" }}>
          <div style={{ fontWeight: 600, color: "var(--mk-danger)" }}>{awaiting.length} need human review</div>
          <div style={{ fontSize: 12, color: "var(--fg-muted)", marginTop: 2 }}>Regulated / customer-facing — never auto-sent. Approve them in the Actions inbox.</div>
        </div>
      )}

      <div className="card card-pad">
        <div style={{ fontWeight: 600, marginBottom: 10 }}>Routed actions</div>
        {rows.length === 0 ? (
          <div style={{ fontSize: 13, color: "var(--fg-muted)" }}>No routed actions yet. They appear here once the router is enabled and calls are classified.</div>
        ) : (
          <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 13 }}>
            <thead>
              <tr style={{ textAlign: "left", color: "var(--fg-muted)" }}>
                <th style={{ padding: "6px 4px", fontWeight: 500 }}>Action</th>
                <th style={{ padding: "6px 4px", fontWeight: 500 }}>Urgency</th>
                <th style={{ padding: "6px 4px", fontWeight: 500 }}>Status</th>
                <th style={{ padding: "6px 4px", fontWeight: 500 }}>SLA due</th>
              </tr>
            </thead>
            <tbody>
              {rows.slice(0, 100).map((r) => (
                <tr key={r.id} style={{ borderTop: "1px solid var(--border, rgba(0,0,0,.08))" }}>
                  <td style={{ padding: "8px 4px" }}>{r.action_type || "action"}</td>
                  <td style={{ padding: "8px 4px", color: URGENCY_TONE[r.urgency_tier] || "var(--fg)" }}>{r.urgency_tier || "—"}</td>
                  <td style={{ padding: "8px 4px", color: "var(--fg-muted)" }}>{r.dispatch_status || "unrouted"}</td>
                  <td style={{ padding: "8px 4px", color: "var(--fg-muted)" }}>{r.sla_due_at ? new Date(r.sla_due_at).toLocaleString() : "—"}</td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>
    </div>
  );
};
