import type { Metadata } from "next";
import type { CSSProperties } from "react";
import Link from "next/link";
import { ArrowUpRight } from "lucide-react";
import { SITE_NAME, getProfilePath } from "@/lib/constants";
import { createAdminClient } from "@/lib/supabase/admin";
import { createClient } from "@/lib/supabase/server";
import { isAccountRestricted } from "@/lib/moderation";
import SiteHeader from "@/components/SiteHeader";
import "../landing.css";

export const dynamic = "force-dynamic";

export const metadata: Metadata = {
  title: `Leaderboard | ${SITE_NAME}`,
  description: `Most-viewed public profiles on ${SITE_NAME}.`,
  alternates: { canonical: "/leaderboard" },
};

export default async function LeaderboardPage({ searchParams }: { searchParams: Promise<{ period?: string }> }) {
  const periodParam = (await searchParams).period;
  const period = periodParam === "week" ? "week" : periodParam === "month" ? "month" : "all";
  const supabase = createAdminClient();

  type LeaderboardItem = {
    id: string;
    username: string;
    display_name?: string | null;
    avatar_url?: string | null;
    accent?: string | null;
    hide_views?: boolean | null;
    moderation_status?: string | null;
    suspended_until?: string | null;
    is_promoter?: boolean | null;
    views: number;
  };

  const userPromise = (async () => {
    try {
      const userClient = await createClient();
      const { data: { user } } = await userClient.auth.getUser();
      if (!user) return { user: null, username: "" };
      const { data: userProfile } = await supabase.from("profiles").select("username").eq("id", user.id).maybeSingle();
      return { user, username: userProfile?.username || "" };
    } catch {
      return { user: null, username: "" };
    }
  })();

  const leaderboardPromise = (async (): Promise<LeaderboardItem[]> => {
    if (period === "all") {
      const { data: profiles } = await supabase
        .from("profiles")
        .select("id, username, display_name, avatar_url, accent, hide_views, moderation_status, suspended_until, is_promoter, views")
        .not("views", "is", null)
        .gte("views", 1)
        .order("views", { ascending: false })
        .limit(100);

      return (profiles || [])
        .map((p) => ({ ...p, views: Number(p.views || 0) }))
        .filter((p) => !p.hide_views && !isAccountRestricted(p.moderation_status, p.suspended_until))
        .slice(0, 50) as LeaderboardItem[];
    } else {
      const start = period === "week"
        ? new Date(Date.now() - 7 * 24 * 60 * 60 * 1000)
        : new Date(new Date().setUTCDate(1));
      start.setUTCHours(0, 0, 0, 0);
      const { data, error } = await supabase.rpc("leaderboard_by_period", { period_start: start.toISOString(), result_limit: 100 });
      if (error) {
        console.error("Leaderboard period query failed:", error);
      }
      const ranked = ((data || []) as { profile_id: string; view_count: number }[]).map((row) => ({ id: row.profile_id, count: Number(row.view_count || 0) }));
      const ids = ranked.map((row) => row.id);
      const { data: profiles } = ids.length
        ? await supabase
            .from("profiles")
            .select("id, username, display_name, avatar_url, accent, hide_views, moderation_status, suspended_until, is_promoter")
            .in("id", ids)
        : { data: [] };

      const byId = new Map<string, NonNullable<typeof profiles>[number]>();
      for (const profile of profiles || []) byId.set(profile.id, profile);
      return ranked
        .map((row) => {
          const profile = byId.get(row.id);
          return profile ? { ...profile, views: row.count } : null;
        })
        .filter((p): p is NonNullable<typeof p> => Boolean(p && !p.hide_views && !isAccountRestricted(p.moderation_status, p.suspended_until)))
        .slice(0, 50) as LeaderboardItem[];
    }
  })();

  const [{ user, username }, leaderboard] = await Promise.all([userPromise, leaderboardPromise]);

  const periodLabel = period === "week" ? "this week" : period === "month" ? "this month" : "all time";

  return (
    <main className="landingShell">
      <SiteHeader user={user ? { id: user.id } : null} username={username ?? undefined} activePath="/leaderboard" showThemeToggle />

      <div className="landingContainer" style={{ paddingTop: 40, paddingBottom: 80 }}>
        <header className="leaderboardHero">
          <div className="leaderboardHeroInfo">
            <div className="landingEyebrow">Community ranks</div>
            <h1>Views leaderboard</h1>
            <p>Top 50 public profiles by {periodLabel} views.</p>
          </div>

          <nav className="leaderboardFilterGroup" aria-label="Leaderboard period">
            {[{ key: "all", label: "All time" }, { key: "month", label: "This month" }, { key: "week", label: "This week" }].map((option) => (
              <Link
                key={option.key}
                href={option.key === "all" ? "/leaderboard" : `/leaderboard?period=${option.key}`}
                className={`leaderboardFilterBtn${period === option.key ? " active" : ""}`}
                aria-current={period === option.key ? "page" : undefined}
              >
                {option.label}
              </Link>
            ))}
          </nav>
        </header>

        <section className="leaderboardTable" aria-label="Profiles ranked by views">
          <div className="leaderboardTableHead" aria-hidden="true">
            <span>#</span>
            <span>Profile</span>
            <span>Views</span>
          </div>
          {leaderboard.length === 0 ? (
            <p className="leaderboardEmpty">No profiles have reached the leaderboard yet. Claim a username and start sharing your page.</p>
          ) : (
            leaderboard.map((profile, index) => {
              const rank = index + 1;
              const name = profile.display_name || profile.username;
              const accent = profile.accent || "#d87878";
              return (
                <Link
                  key={profile.username}
                  href={getProfilePath(profile.username)}
                  className={`leaderboardRow${rank <= 3 ? ` leaderboardRowTop leaderboardRowTop${rank}` : ""}`}
                  style={{ "--profile-accent": accent } as CSSProperties & { "--profile-accent": string }}
                  aria-label={`Rank ${rank}: ${name}, ${Number(profile.views || 0).toLocaleString()} views`}
                >
                  <span className="leaderboardRank">{rank}</span>
                  <span className="leaderboardIdentity">
                    <span className="leaderboardAvatar">
                      {profile.avatar_url ? (
                        // eslint-disable-next-line @next/next/no-img-element
                        <img src={profile.avatar_url} alt="" />
                      ) : (
                        <span aria-hidden="true">{name.slice(0, 1).toUpperCase()}</span>
                      )}
                    </span>
                    <span className="leaderboardNames">
                      <strong style={{ display: "inline-flex", alignItems: "center", gap: 6 }}>
                        {name}
                        {Boolean((profile as { is_promoter?: boolean }).is_promoter) && (
                          <span
                            title="Promoter (sinss.lol in status)"
                            style={{
                              fontSize: 10,
                              fontWeight: 800,
                              padding: "1px 5px",
                              borderRadius: 4,
                              background: "rgba(216, 123, 123, 0.15)",
                              border: "1px solid rgba(216, 123, 123, 0.35)",
                              color: "#d87b7b",
                              lineHeight: 1.2,
                            }}
                          >
                            Promoter
                          </span>
                        )}
                      </strong>
                      <small>@{profile.username}</small>
                    </span>
                  </span>
                  <span className="leaderboardViews">
                    {Number(profile.views || 0).toLocaleString()}
                    <ArrowUpRight className="leaderboardOpenIcon" size={15} aria-hidden="true" />
                  </span>
                </Link>
              );
            })
          )}
        </section>
        <Link href="/" className="leaderboardBack">Back to {SITE_NAME}</Link>
      </div>
    </main>
  );
}
