"use client";

import { useEffect, useState } from "react";
import { format } from "date-fns";
import {
  listUserSessions,
  kickUser,
  getUserStatus,
  type UserSession,
} from "@/lib/admin-rpc";

interface PlatformSessionInfo {
  sessionId: string;
  userId: string;
  username: string | null;
  workspaceId: string | null;
  ipAddress: string | null;
  userAgent: string | null;
  createdAt: string | null;
}

export default function PlatformSessionsPage() {
  const [sessions, setSessions] = useState<PlatformSessionInfo[]>([]);
  const [loading, setLoading] = useState(true);
  const [kicking, setKicking] = useState<string | null>(null);
  const [adminRpcAvailable, setAdminRpcAvailable] = useState(false);

  useEffect(() => { loadSessions(); }, []);

  async function loadSessions() {
    setLoading(true);
    try {
      // Load platform sessions from the app's REST API (Redis-based)
      const res = await fetch("/api/platform/sessions");
      if (!res.ok) {
        setSessions([]);
        return;
      }
      const data = await res.json();
      setSessions(data.sessions || []);
    } catch (e) {
      console.error(e);
      setSessions([]);
    } finally {
      setLoading(false);
    }
  }

  async function handleKickAllSessions(userId: string) {
    if (!confirm(`强制下线用户 ${userId} 的所有会话？`)) return;
    setKicking(userId);
    try {
      if (adminRpcAvailable) {
        await kickUser(userId);
      } else {
        // Fallback: kick sessions via Redis (app REST API)
        const userSessions = sessions.filter((s) => s.userId === userId);
        await Promise.all(
          userSessions.map((s) =>
            fetch("/api/platform/sessions", {
              method: "DELETE",
              headers: { "Content-Type": "application/json" },
              body: JSON.stringify({ sessionId: s.sessionId }),
            })
          )
        );
      }
      loadSessions();
    } finally {
      setKicking(null);
    }
  }

  async function handleKickSession(sessionId: string) {
    if (!confirm("确定强制下线该会话吗？")) return;
    setKicking(sessionId);
    try {
      await fetch("/api/platform/sessions", {
        method: "DELETE",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ sessionId }),
      });
      loadSessions();
    } finally {
      setKicking(null);
    }
  }

  // Group by user
  const byUser = sessions.reduce<Record<string, PlatformSessionInfo[]>>((acc, s) => {
    const key = s.userId || "unknown";
    if (!acc[key]) acc[key] = [];
    acc[key].push(s);
    return acc;
  }, {});

  return (
    <div className="admin-content">
      <div className="page-header" style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
        <div>
          <h1 className="page-title">平台用户在线会话</h1>
          <p className="page-subtitle">
            共 {sessions.length} 个活跃会话，涉及 {Object.keys(byUser).length} 个用户
            {adminRpcAvailable && (
              <span style={{ marginLeft: "8px", color: "#22c55e", fontSize: "12px" }}>
                ● adminrpc 已连接
              </span>
            )}
          </p>
        </div>
        <div style={{ display: "flex", gap: "8px" }}>
          <button
            className="btn btn-secondary"
            onClick={async () => {
              try {
                const { adminRpcHealth } = await import("@/lib/admin-rpc");
                await adminRpcHealth();
                setAdminRpcAvailable(true);
              } catch {
                setAdminRpcAvailable(false);
              }
            }}
          >
            检测 adminrpc
          </button>
          <button className="btn btn-secondary" onClick={loadSessions}>刷新</button>
        </div>
      </div>

      {loading ? (
        <div className="loading">加载中...</div>
      ) : sessions.length === 0 ? (
        <div className="card">
          <div className="empty-state">
            <div className="empty-state-icon">◐</div>
            <p>当前没有在线的平台用户会话</p>
          </div>
        </div>
      ) : (
        Object.entries(byUser).map(([userId, userSessions]) => (
          <div key={userId} className="card" style={{ marginBottom: "16px" }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "12px" }}>
              <div>
                <span style={{ fontWeight: 600 }}>用户 UID: {userId}</span>
                {userSessions[0].username && (
                  <span style={{ marginLeft: "8px", color: "#737373" }}>({userSessions[0].username})</span>
                )}
                <span className="badge badge-neutral" style={{ marginLeft: "8px" }}>
                  {userSessions.length} 个会话
                </span>
                {adminRpcAvailable && (
                  <AdminRpcUserStatus userId={userId} />
                )}
              </div>
              {adminRpcAvailable && (
                <button
                  className="btn btn-danger btn-sm"
                  disabled={kicking === userId}
                  onClick={() => handleKickAllSessions(userId)}
                >
                  {kicking === userId ? "处理中..." : "全部下线 (adminrpc)"}
                </button>
              )}
            </div>

            <div className="table-container">
              <table className="data-table">
                <thead>
                  <tr>
                    <th>Session ID</th>
                    <th>工作空间</th>
                    <th>登录时间</th>
                    <th>IP</th>
                    <th>User Agent</th>
                    <th>操作</th>
                  </tr>
                </thead>
                <tbody>
                  {userSessions.map((s) => (
                    <tr key={s.sessionId}>
                      <td>
                        <code style={{ fontSize: "11px", background: "#f4f4f5", padding: "2px 6px", borderRadius: "4px" }}>
                          {s.sessionId.slice(0, 16)}...
                        </code>
                      </td>
                      <td style={{ fontSize: "12px" }}>
                        {s.workspaceId ? (
                          <code>{s.workspaceId.slice(0, 8)}...</code>
                        ) : "—"}
                      </td>
                      <td>{s.createdAt ? format(new Date(s.createdAt), "yyyy-MM-dd HH:mm") : "—"}</td>
                      <td style={{ fontSize: "13px" }}>{s.ipAddress || "—"}</td>
                      <td
                        style={{ fontSize: "12px", maxWidth: "240px", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}
                        title={s.userAgent || ""}
                      >
                        {s.userAgent || "—"}
                      </td>
                      <td>
                        <button
                          className="btn btn-danger btn-sm"
                          disabled={kicking === s.sessionId}
                          onClick={() => handleKickSession(s.sessionId)}
                        >
                          {kicking === s.sessionId ? "..." : "下线"}
                        </button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        ))
      )}
    </div>
  );
}

// ─── AdminRpc Status Badge ────────────────────────────────────────────────────

function AdminRpcUserStatus({ userId }: { userId: string }) {
  const [status, setStatus] = useState<string | null>(null);

  useEffect(() => {
    getUserStatus(userId)
      .then((r) => setStatus(r.status))
      .catch(() => setStatus(null));
  }, [userId]);

  if (!status) return null;
  const color = status === "Online" ? "#22c55e" : "#f59e0b";
  return (
    <span style={{ marginLeft: "8px", color, fontSize: "12px", fontWeight: 500 }}>
      [{status}]
    </span>
  );
}
