// Active Sessions screen — real-time monitoring table with filters, auto-refresh, and expire actions.
// Default filter: 'active'. Auto-refresh: every 10s, always on.

const { useState, useEffect } = React;

const SessionsScreen = () => {
  const toast = useToast();
  const confirm = useConfirm();
  const { data: sessions, loading, error, refetch } = useApi(ActiveSessionApi.list, []);
  const [filter, setFilter] = useState("active");
  const [expiring, setExpiring] = useState(null); // id of session being expired

  // Auto-refresh every 10s
  useEffect(() => {
    const interval = setInterval(refetch, 10000);
    return () => clearInterval(interval);
  }, []);

  const all = sessions || [];

  // Computed KPI stats
  const total       = all.length;
  const activeCount = all.filter(s => s.status === "active").length;
  const expiredCount = all.filter(s => s.status === "expired").length;
  const avgMessages = total > 0
    ? Math.round(all.reduce((sum, s) => sum + (s.messages_count || 0), 0) / total)
    : 0;

  // Apply status filter
  const filtered = filter === "all" ? all : all.filter(s => s.status === filter);

  const handleExpire = async (id) => {
    setExpiring(id);
    try {
      await ActiveSessionApi.expire(id);
      toast.success("Session expired");
      refetch();
    } catch (e) {
      toast.error(e.message);
    } finally {
      setExpiring(null);
    }
  };

  const handleExpireInactive = async () => {
    const ok = await confirm("Expire inactive sessions", "This will expire all inactive sessions. Continue?");
    if (!ok) return;
    try {
      await ActiveSessionApi.expireInactive();
      toast.success("Inactive sessions expired");
      refetch();
    } catch (e) {
      toast.error(e.message);
    }
  };

  return (
    <div className="page">
      <div className="page-head">
        <div>
          <h1 className="page-title">Active Sessions</h1>
          <div className="page-sub">
            {loading ? "Loading…" : `${activeCount} active · ${expiredCount} expired`}
          </div>
        </div>
        <div style={{ display: "flex", gap: 8 }}>
          <button className="btn ghost" onClick={handleExpireInactive}>Expire Inactive</button>
          <button className="btn" onClick={refetch}><I.Refresh /> Refresh</button>
        </div>
      </div>

      {/* KPI stats row */}
      <div className="kpi-row">
        <Kpi label="Total sessions"       value={loading ? "…" : total} />
        <Kpi label="Active"               value={loading ? "…" : activeCount} />
        <Kpi label="Expired"              value={loading ? "…" : expiredCount} />
        <Kpi label="Avg messages/session" value={loading ? "…" : avgMessages} />
      </div>

      {/* Status filter chips */}
      <div className="chip-group" style={{ marginBottom: 12 }}>
        {[
          { id: "all",     label: "All" },
          { id: "active",  label: "Active" },
          { id: "expired", label: "Expired" },
        ].map(({ id, label }) => (
          <button
            key={id}
            className={`chip ${filter === id ? "active" : ""}`}
            onClick={() => setFilter(id)}
          >
            {label}
          </button>
        ))}
      </div>

      <Card flush>
        <table className="table">
          <thead>
            <tr>
              <th>User</th>
              <th>Source Group</th>
              <th>Assigned Bot</th>
              <th>Status</th>
              <th>Topic</th>
              <th>Messages</th>
              <th>Last Activity</th>
              <th style={{ width: 90 }}>Actions</th>
            </tr>
          </thead>
          <tbody>
            {loading ? (
              <SkeletonRows cols={8} rows={4} />
            ) : error ? (
              <tr><td colSpan={8}><Empty icon={I.AlertTriangle} title="Error" sub={error} /></td></tr>
            ) : filtered.length === 0 ? (
              <tr><td colSpan={8}><Empty icon={I.Radio} title="No sessions" sub="No sessions found for the selected filter." /></td></tr>
            ) : (
              filtered.map((s) => {
                const sourceGroup = s.source_group_id;
                const bot = s.assigned_bot_id;
                return (
                  <tr key={s._id}>
                    <td>
                      <div style={{ fontWeight: 500 }}>{s.display_name || s.username || "—"}</div>
                      {s.username && (
                        <div className="mono muted" style={{ fontSize: 11 }}>@{s.username}</div>
                      )}
                      {s.user_telegram_id && (
                        <div className="muted" style={{ fontSize: 11 }}>{s.user_telegram_id}</div>
                      )}
                    </td>
                    <td>
                      {typeof sourceGroup === "object"
                        ? (sourceGroup?.name || "—")
                        : (sourceGroup || "—")}
                    </td>
                    <td>
                      {typeof bot === "object" ? (
                        <>
                          <div>{bot?.name || "—"}</div>
                          {bot?.phone && (
                            <div className="mono muted" style={{ fontSize: 11 }}>{bot.phone}</div>
                          )}
                        </>
                      ) : (bot || "—")}
                    </td>
                    <td><StatusBadge status={s.status} /></td>
                    <td>
                      {s.topic_id
                        ? <span className="mono">#{s.topic_id}</span>
                        : <span className="muted">—</span>}
                    </td>
                    <td>{s.messages_count ?? 0}</td>
                    <td className="muted">{relativeTime(s.last_activity)}</td>
                    <td>
                      {s.status === "active" && (
                        <button
                          className="btn ghost sm"
                          onClick={() => handleExpire(s._id)}
                          disabled={expiring === s._id}
                        >
                          {expiring === s._id ? "…" : "Expire"}
                        </button>
                      )}
                    </td>
                  </tr>
                );
              })
            )}
          </tbody>
        </table>
      </Card>
      <div className="muted" style={{ fontSize: 12, marginTop: 8 }}>
        Auto-refreshes every 10s
      </div>
    </div>
  );
};

Object.assign(window, { SessionsScreen });
