import { getAuthenticatedUser } from "@/auth";
import { getLoginEvents, getUserHas2FA, getUserSessions } from "@/lib/keycloak";
import { getUserActivity } from "@/database/activity";
import { getUserByGscsid } from "@/database/users";
import UserAnalytics from "@/components/account/UserAnalytics";

export default async function AnalyticsPage() {
  const user = await getAuthenticatedUser();

  let loginSessions: Array<{
    id: string;
    loginTime: string;
    ipAddress: string;
    device: string;
    location: string;
    status: "success" | "failed";
  }> = [];

  let recentActivity: Array<{
    id: string;
    action: string;
    target: string;
    timestamp: string;
    icon: string;
    color: string;
  }> = [];

  let memberSince: string | null = null;
  let twoFactorEnabled = false;
  let activeSessionCount = 0;

  // Fetch Keycloak login events, 2FA status, and active sessions
  if (user?.keycloakId) {
    try {
      const [events, has2FA, sessions] = await Promise.all([
        getLoginEvents(user.keycloakId, 20),
        getUserHas2FA(user.keycloakId),
        getUserSessions(user.keycloakId),
      ]);
      twoFactorEnabled = has2FA;
      activeSessionCount = sessions.length;
      loginSessions = events.map((e, i) => ({
        id: String(i),
        loginTime: new Date(e.time).toISOString(),
        ipAddress: e.ipAddress || "Unknown",
        device: e.details?.user_agent ? parseUserAgent(e.details.user_agent) : "Unknown",
        location: "—",
        status: e.type === "LOGIN" ? "success" as const : "failed" as const,
      }));
    } catch (err) {
      console.warn("[analytics page] Keycloak fetch error:", err);
    }
  }

  // Fetch activity log and member-since date from DB
  if (user?.gscUserId) {
    try {
      const activities = await getUserActivity(user.gscUserId, { limit: 20 });
      recentActivity = activities.map((a) => ({
        id: a.id,
        action: a.action,
        target: a.target || "",
        timestamp: a.createdAt.toISOString(),
        icon: activityIcon(a.action),
        color: activityColor(a.action),
      }));
    } catch (err) {
      console.warn("[analytics page] Activity fetch error:", err);
    }

    // Get member since
    if (user.gscsid) {
      try {
        const dbUser = await getUserByGscsid(user.gscsid);
        if (dbUser?.createdAt) {
          memberSince = dbUser.createdAt.toISOString();
        }
      } catch {
        // ignore
      }
    }
  }

  return (
    <UserAnalytics
      userName={user?.displayName || "User"}
      userEmail={user?.email || ""}
      loginSessions={loginSessions}
      recentActivity={recentActivity}
      memberSince={memberSince}
      twoFactorEnabled={twoFactorEnabled}
      activeSessionCount={activeSessionCount}
    />
  );
}

function parseUserAgent(ua: string): string {
  if (ua.includes("Chrome") && !ua.includes("Edge")) {
    if (ua.includes("Windows")) return "Chrome on Windows";
    if (ua.includes("Mac")) return "Chrome on macOS";
    if (ua.includes("Linux")) return "Chrome on Linux";
    return "Chrome";
  }
  if (ua.includes("Firefox")) {
    if (ua.includes("Windows")) return "Firefox on Windows";
    if (ua.includes("Mac")) return "Firefox on macOS";
    return "Firefox";
  }
  if (ua.includes("Safari") && !ua.includes("Chrome")) {
    if (ua.includes("iPhone") || ua.includes("iPad")) return "Safari on iOS";
    return "Safari on macOS";
  }
  if (ua.includes("Edge")) return "Edge on Windows";
  return "Unknown";
}

function activityIcon(action: string): string {
  const map: Record<string, string> = {
    Opened: "ph-house", Configured: "ph-gear", Browsed: "ph-storefront",
    Viewed: "ph-eye", Updated: "ph-pencil", Accessed: "ph-envelope",
    Created: "ph-plus", Deleted: "ph-trash", Login: "ph-sign-in",
  };
  return map[action] || "ph-activity";
}

function activityColor(action: string): string {
  const map: Record<string, string> = {
    Opened: "primary", Configured: "info", Browsed: "success",
    Viewed: "secondary", Updated: "warning", Accessed: "primary",
    Created: "success", Deleted: "danger", Login: "success",
  };
  return map[action] || "secondary";
}
