"use client";

import { useEffect, useState } from "react";
import { format } from "date-fns";

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

export default function SessionsPage() {
  const [sessions, setSessions] = useState<SessionInfo[]>([]);
  const [loading, setLoading] = useState(true);
  const [kicking, setKicking] = useState<string | null>(null);

  useEffect(() => { loadSessions(); }, []);
  async function loadSessions() {
    setLoading(true);
    try {
      const res = await fetch("/api/sessions");
      const data = await res.json();
      setSessions(data.sessions || []);
    } catch (e) { console.error(e); }
    finally { setLoading(false); }
  }

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

  const byUser = sessions.reduce<Record<string, SessionInfo[]>>((acc, s) => {
    const key = s.userId || "anonymous";
    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} 个用户</p>
        </div>
        <button className="btn btn-secondary" onClick={loadSessions}>刷新</button>
      </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 }}>
                {userId && userSessions[0].username
                  ? `${userSessions[0].username} (ID: ${userId})`
                  : userId === "anonymous" ? "匿名会话" : `用户 ID: ${userId}`}
              </span>
                <span className="badge badge-neutral" style={{ marginLeft: "8px" }}>{userSessions.length} 个会话</span>
              </div>
              {userId !== "anonymous" && (
                <button className="btn btn-danger btn-sm" onClick={async () => {
                  if (!confirm(`强制下线用户 ${userId} 的所有会话？`)) return;
                  for (const s of userSessions) await fetch("/api/sessions", { method: "DELETE", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ sessionId: s.sessionId }) });
                  loadSessions();
                }}>全部下线</button>
              )}
            </div>
            <div className="table-container">
              <table className="data-table">
                <thead><tr><th>Session ID</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>{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: "300px", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{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>
  );
}
