// Path: src/components/admin/security/SessionsPanel.tsx
"use client";

import { useCallback, useEffect, useState } from "react";

interface SessionItem {
  id: string;
  device: string;
  ipAddress: string | null;
  current: boolean;
  active: boolean;
  createdSecondsAgo: number;
  lastActiveSecondsAgo: number;
  endedSecondsAgo: number | null;
  endReason: string | null;
}

const END_REASON: Record<string, string> = {
  logout: "Signed out",
  replaced: "Replaced by a newer sign-in",
  password_changed: "Password changed",
  idle_timeout: "Timed out (inactive)",
  expired: "Expired",
  forced: "Signed out by an administrator",
  terminated: "Account terminated",
  token_reuse: "Blocked: cookie reuse detected",
  device_mismatch: "Blocked: used from another browser",
};

function ago(seconds: number): string {
  if (seconds < 60) return "just now";
  const units: [number, string][] = [[86400, "day"], [3600, "hour"], [60, "minute"]];
  for (const [size, name] of units) {
    if (seconds >= size) {
      const n = Math.floor(seconds / size);
      return `${n} ${name}${n === 1 ? "" : "s"} ago`;
    }
  }
  return "just now";
}

export default function SessionsPanel() {
  const [sessions, setSessions] = useState<SessionItem[] | null>(null);
  const [error, setError] = useState("");
  const [busy, setBusy] = useState<string | null>(null);

  const load = useCallback(async () => {
    try {
      const res = await fetch("/api/auth/sessions", { cache: "no-store" });
      const data = await res.json();
      if (!res.ok || !data.success) throw new Error(data.message ?? "Failed to load sessions");
      setSessions(data.data.sessions);
      setError("");
    } catch (e) {
      setError(e instanceof Error ? e.message : "Failed to load sessions");
    }
  }, []);

  useEffect(() => {
    // eslint-disable-next-line react-hooks/set-state-in-effect -- initial fetch
    load();
  }, [load]);

  async function revoke(body: { action: "revoke"; id: string } | { action: "revoke_others" }) {
    setBusy(body.action === "revoke" ? body.id : "others");
    try {
      const res = await fetch("/api/auth/sessions", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(body),
      });
      const data = await res.json();
      if (!res.ok || !data.success) throw new Error(data.message ?? "Failed");
      await load();
    } catch (e) {
      setError(e instanceof Error ? e.message : "Failed");
    } finally {
      setBusy(null);
    }
  }

  const active = sessions?.filter((s) => s.active) ?? [];
  const history = sessions?.filter((s) => !s.active) ?? [];
  const others = active.filter((s) => !s.current);

  const card: React.CSSProperties = {
    background: "var(--color-surface)",
    border: "1px solid var(--color-border)",
    borderRadius: 16,
  };

  return (
    <div className="flex flex-col gap-6">
      {error && (
        <div className="px-4 py-3 rounded-xl text-sm" style={{ background: "rgba(239,68,68,0.1)", color: "var(--color-danger)" }}>
          {error}
        </div>
      )}

      <section style={card} className="p-5">
        <div className="flex items-center justify-between gap-3 flex-wrap mb-4">
          <h2 className="text-base font-semibold" style={{ color: "var(--color-text)" }}>Active sessions</h2>
          {others.length > 0 && (
            <button
              onClick={() => revoke({ action: "revoke_others" })}
              disabled={busy !== null}
              className="px-3 py-2 rounded-xl text-xs font-semibold disabled:opacity-60"
              style={{ background: "rgba(239,68,68,0.1)", color: "var(--color-danger)" }}
            >
              {busy === "others" ? "Signing out..." : "Sign out all other sessions"}
            </button>
          )}
        </div>

        {sessions === null && !error && <p className="text-sm" style={{ color: "var(--color-text-muted)" }}>Loading...</p>}

        <ul className="flex flex-col gap-3">
          {active.map((s) => (
            <li key={s.id} className="flex items-start justify-between gap-3 p-3 rounded-xl" style={{ background: "var(--color-surface-alt)" }}>
              <div className="min-w-0">
                <p className="text-sm font-medium flex items-center gap-2 flex-wrap" style={{ color: "var(--color-text)" }}>
                  {s.device}
                  {s.current && (
                    <span className="text-[11px] px-2 py-0.5 rounded-full" style={{ background: "rgba(5,150,105,0.12)", color: "var(--color-success)" }}>
                      This browser
                    </span>
                  )}
                </p>
                <p className="text-xs mt-0.5" style={{ color: "var(--color-text-muted)" }}>
                  {s.ipAddress ?? "Unknown IP"} · signed in {ago(s.createdSecondsAgo)} · last active {ago(s.lastActiveSecondsAgo)}
                </p>
              </div>
              {!s.current && (
                <button
                  onClick={() => revoke({ action: "revoke", id: s.id })}
                  disabled={busy !== null}
                  className="shrink-0 text-xs font-semibold hover:opacity-80 disabled:opacity-60"
                  style={{ color: "var(--color-danger)" }}
                >
                  {busy === s.id ? "..." : "Sign out"}
                </button>
              )}
            </li>
          ))}
        </ul>
      </section>

      {history.length > 0 && (
        <section style={card} className="p-5">
          <h2 className="text-base font-semibold mb-4" style={{ color: "var(--color-text)" }}>Recent sign-ins (last 30 days)</h2>
          <ul className="flex flex-col divide-y" style={{ borderColor: "var(--color-border)" }}>
            {history.map((s) => {
              const alarming = s.endReason === "token_reuse" || s.endReason === "device_mismatch";
              return (
                <li key={s.id} className="py-2.5 flex items-start justify-between gap-3">
                  <div className="min-w-0">
                    <p className="text-sm" style={{ color: "var(--color-text)" }}>{s.device}</p>
                    <p className="text-xs mt-0.5" style={{ color: "var(--color-text-muted)" }}>
                      {s.ipAddress ?? "Unknown IP"} · signed in {ago(s.createdSecondsAgo)}
                    </p>
                  </div>
                  <span className="shrink-0 text-xs text-right" style={{ color: alarming ? "var(--color-danger)" : "var(--color-text-muted)" }}>
                    {END_REASON[s.endReason ?? ""] ?? s.endReason}
                    {s.endedSecondsAgo !== null && <><br />{ago(s.endedSecondsAgo)}</>}
                  </span>
                </li>
              );
            })}
          </ul>
        </section>
      )}
    </div>
  );
}
