/* Monitoring.jsx — моніторинг у реальному часі (live API). */

const { useState: useStateM, useEffect: useEffectM } = React;

function Monitoring({ onNav }) {
  const [data, setData] = useStateM(null);
  const [loading, setLoading] = useStateM(true);
  const [error, setError] = useStateM(null);
  const [filter, setFilter] = useStateM("all");
  const [acked, setAcked] = useStateM(new Set());
  const [lastUpdate, setLastUpdate] = useStateM(new Date());

  const reload = async () => {
    try {
      const res = await window.passengerApi.monitoring.snapshot();
      setData(res);
      setLastUpdate(new Date());
      setError(null);
    } catch (e) {
      setError(e);
      window.showToast && window.showToast("Не вдалося завантажити Моніторинг: " + (e.message || ""), "bad");
    } finally {
      setLoading(false);
    }
  };

  useEffectM(() => { reload(); }, []);
  window.passengerApi.usePolling(reload, 30000, []);

  const kpi = (data && data.kpi) || {};
  const alerts = (data && data.alerts) || [];
  const routes = (data && data.routes) || [];

  const handleAck = async (alert) => {
    try {
      await window.passengerApi.monitoring.ack({
        central_id: alert.central_id,
        code: alert.code,
      });
      setAcked(prev => new Set([...prev, alert.id]));
      window.showToast && window.showToast(`${alert.central_id} підтверджено — алерт закрито`, "ok");
      await reload();
    } catch (e) {
      window.showToast && window.showToast("Помилка ack: " + (e.message || ""), "bad");
    }
  };

  const handleAckAll = async () => {
    const targets = alerts.filter(a => !acked.has(a.id) && a.severity === "bad");
    if (!targets.length) return;
    try {
      const results = await Promise.allSettled(
        targets.map(a => window.passengerApi.monitoring.ack({ central_id: a.central_id, code: a.code }))
      );
      const ok = results.filter(r => r.status === "fulfilled").length;
      const failed = results.length - ok;
      setAcked(prev => {
        const next = new Set(prev);
        targets.forEach(a => next.add(a.id));
        return next;
      });
      window.showToast && window.showToast(`Підтверджено ${ok}${failed ? `, помилок ${failed}` : ""}`, ok ? "ok" : "warn");
      await reload();
    } catch (e) {
      window.showToast && window.showToast("Помилка bulk-ack: " + (e.message || ""), "bad");
    }
  };

  const filteredAlerts = alerts.filter(a => {
    if (filter === "problems") return a.severity === "bad" && !acked.has(a.id);
    if (filter === "ok")       return a.severity !== "bad" || acked.has(a.id);
    return true;
  });

  const fmtTime = (d) => d.toLocaleTimeString("uk-UA", { hour: "2-digit", minute: "2-digit" });

  return (
    <>
      <Topbar
        title="Моніторинг"
        subtitle={loading && !data ? "Завантаження…" : `Оновлено о ${fmtTime(lastUpdate)}`}
        actions={
          <div style={{ display: "flex", gap: 8 }}>
            {kpi.problems > 0 && (
              <button className="btn btn-secondary btn-sm" onClick={handleAckAll}>
                ✓ Підтвердити всі ({kpi.problems})
              </button>
            )}
            <button className="btn btn-secondary btn-sm" onClick={async () => { await reload(); window.showToast && window.showToast("Дані оновлено", "ok"); }}>
              ⟳ Оновити
            </button>
          </div>
        }
      />

      <div className="page" style={{ animation: "fadeIn 0.2s ease" }}>

        {error && (
          <div className="alert-banner bad">
            <span>Помилка завантаження.</span>
            <button className="btn btn-sm btn-secondary" onClick={reload}>Спробувати знову</button>
          </div>
        )}

        {/* KPI row */}
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 12, marginBottom: 20 }}>
          {[
            { label: "Проблемні узли", value: kpi.problems != null ? kpi.problems : "—",
              color: (kpi.problems || 0) > 0 ? "var(--bad)" : "var(--ok)",
              bg: (kpi.problems || 0) > 0 ? "var(--bad-bg)" : "var(--ok-bg)",
              border: (kpi.problems || 0) > 0 ? "var(--bad-border)" : "var(--ok-border)" },
            { label: "ТЗ онлайн", value: kpi.vehicles_label || "—",
              color: "var(--text-1)", bg: "var(--surface)", border: "var(--border)" },
            { label: "Середня доступність", value: kpi.avg_availability_pct != null ? `${kpi.avg_availability_pct}%` : "—",
              color: (kpi.avg_availability_pct || 0) >= 95 ? "var(--ok)" : "var(--warn)",
              bg: (kpi.avg_availability_pct || 0) >= 95 ? "var(--ok-bg)" : "var(--warn-bg)",
              border: (kpi.avg_availability_pct || 0) >= 95 ? "var(--ok-border)" : "var(--warn-border)" },
            { label: "Інциденти", value: kpi.incidents_open != null ? kpi.incidents_open : "—",
              color: (kpi.incidents_open || 0) > 0 ? "var(--warn)" : "var(--text-1)",
              bg: (kpi.incidents_open || 0) > 0 ? "var(--warn-bg)" : "var(--surface)",
              border: (kpi.incidents_open || 0) > 0 ? "var(--warn-border)" : "var(--border)" },
          ].map((k, i) => (
            <div key={i} style={{ background: k.bg, border: `1px solid ${k.border}`, borderRadius: "var(--radius)", padding: "14px 16px" }}>
              <div style={{ fontSize: 11, fontWeight: 600, textTransform: "uppercase", letterSpacing: "0.5px", color: "var(--text-3)", marginBottom: 6 }}>{k.label}</div>
              <div style={{ fontSize: 26, fontWeight: 700, color: k.color, letterSpacing: "-0.5px" }}>{k.value}</div>
            </div>
          ))}
        </div>

        {/* Alerts list (admin/fleet alerts) */}
        <div className="card" style={{ padding: 0, overflow: "hidden", marginBottom: 16 }}>
          <div style={{ padding: "12px 16px", borderBottom: "1px solid var(--border)", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
            <div className="segmented">
              <button className={filter === "all" ? "active" : ""} onClick={() => setFilter("all")}>
                Усі {alerts.length}
              </button>
              <button className={filter === "problems" ? "active" : ""} onClick={() => setFilter("problems")}
                style={{ color: filter !== "problems" && (kpi.problems || 0) > 0 ? "var(--bad)" : undefined }}>
                Проблеми {kpi.problems || 0}
              </button>
              <button className={filter === "ok" ? "active" : ""} onClick={() => setFilter("ok")}>
                Норма
              </button>
            </div>
            <span style={{ fontSize: 12, color: "var(--text-3)" }}>
              Авто-оновлення кожні 30 с
            </span>
          </div>

          {filteredAlerts.length === 0 ? (
            <div style={{ padding: 40, textAlign: "center", color: "var(--text-3)" }}>
              <div style={{ fontSize: 22, marginBottom: 6 }}>{kpi.problems ? "🔍" : "✅"}</div>
              <div style={{ fontSize: 14 }}>
                {kpi.problems ? `Усі ${kpi.problems} критичних оброблено в цій вкладці` : "Алертів немає"}
              </div>
            </div>
          ) : (
            <table className="table">
              <thead>
                <tr>
                  <th>Узел / код</th>
                  <th>Серйозність</th>
                  <th>Повідомлення</th>
                  <th>Вік</th>
                  <th></th>
                </tr>
              </thead>
              <tbody>
                {filteredAlerts.map(a => {
                  const isAcked = acked.has(a.id) || a.acked_at;
                  return (
                    <tr key={a.id} style={{ background: a.severity === "bad" && !isAcked ? "var(--bad-bg)" : undefined }}>
                      <td>
                        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                          <span className={"dot dot-" + (isAcked ? "muted" : a.severity === "bad" ? "bad" : a.severity === "warn" ? "warn" : "ok")}></span>
                          <div>
                            <div style={{ fontWeight: 600 }}>{a.central_id || "—"}</div>
                            <div style={{ fontSize: 12, color: "var(--text-3)", fontFamily: "monospace" }}>{a.code}</div>
                          </div>
                        </div>
                      </td>
                      <td>
                        {isAcked
                          ? <span className="badge badge-neutral">✓ Підтверджено</span>
                          : a.severity === "bad"
                            ? <span className="badge badge-bad">⚠ Проблема</span>
                            : a.severity === "warn"
                              ? <span className="badge badge-warn">⚡ Попередження</span>
                              : <span className="badge badge-ok">✓ Норма</span>}
                      </td>
                      <td style={{ fontSize: 13 }}>{a.message || "—"}</td>
                      <td><span className="mono" style={{ color: "var(--text-3)" }}>{a.age_label || ""}</span></td>
                      <td>
                        {!isAcked && (
                          <button className="btn btn-secondary btn-xs" onClick={() => handleAck(a)}>✓ Ack</button>
                        )}
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          )}
        </div>

        {/* Routes list (passenger_routes) */}
        {routes.length > 0 && (
          <div className="card" style={{ padding: 0, overflow: "hidden" }}>
            <div className="card-header">
              <span className="card-title">Маршрути ({routes.length})</span>
              <button className="btn btn-ghost btn-sm" onClick={() => onNav("routes")}>До маршрутів →</button>
            </div>
            <table className="table">
              <thead>
                <tr>
                  <th>Маршрут</th>
                  <th>Статус</th>
                  <th>Призупинено</th>
                  <th></th>
                </tr>
              </thead>
              <tbody>
                {routes.map(r => (
                  <tr key={r.id}>
                    <td>
                      <div style={{ fontWeight: 600 }}>{r.code}</div>
                      <div style={{ fontSize: 12, color: "var(--text-3)" }}>{r.name}</div>
                    </td>
                    <td>
                      {r.paused
                        ? <span className="badge badge-warn">⏸ Призупинено</span>
                        : r.status === "published"
                          ? <span className="badge badge-ok">● Активний</span>
                          : <span className="badge badge-neutral">○ Чернетка</span>}
                    </td>
                    <td style={{ fontSize: 12, color: "var(--text-3)" }}>
                      {r.paused_reason || (r.paused ? "—" : "")}
                    </td>
                    <td>
                      <button className="btn btn-ghost btn-xs" onClick={() => onNav("routes")}>Деталі →</button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}

      </div>
    </>
  );
}

Object.assign(window, { Monitoring });
