// Alerts.jsx — live alerts screen backed by /api/v1/alerts

function Alerts() {
  const [alerts, setAlerts] = React.useState([]);
  const [statusRows, setStatusRows] = React.useState([]);
  const [summaryCounts, setSummaryCounts] = React.useState({ active: 0, closed: 0 });
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState("");
  const [severityTab, setSeverityTab] = React.useState("all");
  const [statusTab, setStatusTab] = React.useState("active");
  const [pendingAck, setPendingAck] = React.useState({});
  const [rowErrors, setRowErrors] = React.useState({});

  const loadAlerts = React.useCallback(async () => {
    // [TASK_START:T007]
    const statusFilter = statusTab === "active" ? "open" : "closed";
    // [TASK_COMPLETE:T007]
    // [TASK_START:T008]
    const severityFilter = severityTab === "all" ? undefined : severityTab;
    // [TASK_COMPLETE:T008]

    setLoading(true);
    setError("");

    try {
      // [TASK_START:T006]
      const [statusScopedRows, filteredRows, openRows, closedRows] = await Promise.all([
        Keeper.api.alerts({ status: statusFilter }),
        Keeper.api.alerts({ status: statusFilter, severity: severityFilter }),
        Keeper.api.alerts({ status: "open" }),
        Keeper.api.alerts({ status: "closed" }),
      ]);
      // [TASK_COMPLETE:T006]

      setStatusRows(Array.isArray(statusScopedRows) ? statusScopedRows : []);
      setAlerts(Array.isArray(filteredRows) ? filteredRows : []);
      setSummaryCounts({
        active: Array.isArray(openRows) ? openRows.length : 0,
        closed: Array.isArray(closedRows) ? closedRows.length : 0,
      });
    } catch (e) {
      // [TASK_START:T011]
      setStatusRows([]);
      setAlerts([]);
      setSummaryCounts({ active: 0, closed: 0 });
      const fallbackMessage = "Не удалось загрузить уведомления. Повторите попытку.";
      const formatted = typeof Keeper.formatApiFailure === "function"
        ? Keeper.formatApiFailure(e, { fallbackMessage })
        : fallbackMessage;
      setError(formatted);
      // [TASK_COMPLETE:T011]
    } finally {
      setLoading(false);
    }
  }, [severityTab, statusTab]);

  React.useEffect(() => {
    let cancelled = false;
    (async () => {
      await loadAlerts();
      if (cancelled) return;
    })();
    return () => {
      cancelled = true;
    };
  }, [loadAlerts]);

  function isActive(alert) {
    return alert.status === "open" || alert.status === "active";
  }

  const counts = {
    all: statusRows.length,
    crit: statusRows.filter((a) => (a.severity || a.kind) === "crit").length,
    warn: statusRows.filter((a) => (a.severity || a.kind) === "warn").length,
    info: statusRows.filter((a) => (a.severity || a.kind) === "info").length,
    active: summaryCounts.active,
    closed: summaryCounts.closed,
  };

  // [TASK_START:T009]
  async function acknowledgeAlert(id) {
    const current = alerts.find((a) => a.id === id);
    if (!current || !isActive(current)) return;

    setPendingAck((m) => ({ ...m, [id]: true }));
    setRowErrors((m) => ({ ...m, [id]: "" }));

    const prevStatus = current.status;
    setAlerts((rows) => rows.map((a) => (a.id === id ? { ...a, status: "acknowledged" } : a)));

    try {
      const updated = await Keeper.api.ackAlert(id);
      const nextStatus = (updated && updated.status) || "acknowledged";
      setAlerts((rows) => rows.map((a) => (a.id === id ? { ...a, status: nextStatus } : a)));
      await loadAlerts();
    } catch (e) {
      setAlerts((rows) => rows.map((a) => (a.id === id ? { ...a, status: prevStatus } : a)));
      const fallbackMessage = "Не удалось подтвердить уведомление";
      const formatted = typeof Keeper.formatApiFailure === "function"
        ? Keeper.formatApiFailure(e, { fallbackMessage })
        : fallbackMessage;
      setRowErrors((m) => ({ ...m, [id]: formatted }));
    } finally {
      setPendingAck((m) => ({ ...m, [id]: false }));
    }
  }
  // [TASK_COMPLETE:T009]

  return (
    <div className="page">
      <div className="page-head">
        <div>
          <div className="page-title">Уведомления</div>
          <div className="page-sub">{counts.active} активные · {counts.closed} закрытые</div>
        </div>
        <div className="actions">
          <div className="segmented">
            <button
              className={statusTab === "active" ? "on" : ""}
              onClick={() => setStatusTab("active")}
            >
              Активные · {counts.active}
            </button>
            <button
              className={statusTab === "closed" ? "on" : ""}
              onClick={() => setStatusTab("closed")}
            >
              Закрытые · {counts.closed}
            </button>
          </div>
        </div>
      </div>

      <div className="tab-bar">
        <button className={"tab " + (severityTab === "all" ? "active" : "")} onClick={() => setSeverityTab("all")}>Все · {counts.all}</button>
        <button className={"tab " + (severityTab === "crit" ? "active" : "")} onClick={() => setSeverityTab("crit")}>Критические · {counts.crit}</button>
        <button className={"tab " + (severityTab === "warn" ? "active" : "")} onClick={() => setSeverityTab("warn")}>Предупреждения · {counts.warn}</button>
        <button className={"tab " + (severityTab === "info" ? "active" : "")} onClick={() => setSeverityTab("info")}>Информация · {counts.info}</button>
      </div>

      {loading && (
        <div className="card" style={{ padding: 16, color: "var(--fg-muted)" }}>
          Загрузка уведомлений...
        </div>
      )}

      {!loading && error && (
        <div className="card" style={{ padding: 16, color: "#9a1f18", background: "#FCE2E0", borderColor: "#F5B3AD" }}>
          {error}
        </div>
      )}

      {/* [TASK_START:T010] */}
      {!loading && !error && alerts.length === 0 && (
        <div className="card" style={{ padding: 16, color: "var(--fg-muted)" }}>
          Нет уведомлений
        </div>
      )}
      {/* [TASK_COMPLETE:T010] */}

      {!loading && !error && alerts.map((a) => {
        const rowKind = a.severity || a.kind;
        const canAck = isActive(a);
        const ackBusy = !!pendingAck[a.id];
        return (
          <div key={a.id} className={"alert-row " + rowKind} style={{ gridTemplateColumns: "32px 1fr 120px 120px auto auto", alignItems: "center" }}>
            <div className="ic"><i className={a.icon}></i></div>
            <div>
              <div className="alert-title">{a.title}</div>
              <div className="alert-sub">{a.sub}</div>
              {rowErrors[a.id] && (
                <div style={{ fontSize: 12, color: "#9a1f18", marginTop: 4 }}>{rowErrors[a.id]}</div>
              )}
            </div>
            <span style={{ fontSize: 12, color: "var(--fg-muted)" }}>{a.zone || "—"}</span>
            <span style={{ fontSize: 12, color: "var(--fg-muted)" }}>{a.who || "—"}</span>
            <span className="alert-time">{a.time}</span>
            {canAck ? (
              <button
                className="btn btn--secondary btn--sm"
                disabled={ackBusy}
                onClick={() => acknowledgeAlert(a.id)}
              >
                {ackBusy ? "Подтверждение..." : "Отметить прочитанным"}
              </button>
            ) : (
              <span className="status status--muted" style={{ minWidth: 120, justifyContent: "center" }}>
                <span className="dot"></span>
                {a.status === "acknowledged" ? "Подтверждено" : "Закрыто"}
              </span>
            )}
          </div>
        );
      })}
    </div>
  );
}

window.Alerts = Alerts;
