import { ImageResponse } from "next/og";
import { type NextRequest } from "next/server";
import { createAdminClient } from "@/lib/supabase/admin";
import { isAccountRestricted } from "@/lib/moderation";
import { badgesForProfile } from "@/lib/profile-badges";
import type { Profile } from "@/lib/constants";

export const dynamic = "force-dynamic";

const WIDTH = 1200;
const HEIGHT = 440;

function isSafeSatoriImageUrl(url: unknown): url is string {
  if (typeof url !== "string") return false;
  const trimmed = url.trim();
  if (!/^https?:\/\//i.test(trimmed)) return false;
  const lower = trimmed.split("?")[0].toLowerCase();
  if (lower.endsWith(".mp4") || lower.endsWith(".webm") || lower.endsWith(".mov") || lower.endsWith(".webp") || lower.endsWith(".avif") || lower.endsWith(".svg")) {
    return false;
  }
  return true;
}

export async function GET(_request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  if (!/^[0-9]{15,25}$/.test(id)) {
    return new Response("Invalid Discord user ID", { status: 400 });
  }

  let admin;
  try {
    admin = createAdminClient();
  } catch {
    return new Response("Unavailable", { status: 503 });
  }

  const { data, error } = await admin
    .from("profiles")
    .select(
      "username,display_name,alias,hide_alias,bio,avatar_url,background_url,accent,public_uid,views,hide_views,like_count,hide_likes,links,badges,admin_badge_ids,created_at,hide_join_date,credits,daily_streak,layout,moderation_status,suspended_until"
    )
    .eq("discord_id", id)
    .maybeSingle();

  if (error || !data || isAccountRestricted(data.moderation_status, data.suspended_until)) {
    return new Response("Profile not found", { status: 404 });
  }

  const accent = typeof data.accent === "string" && /^#[0-9a-f]{6}$/i.test(data.accent) ? data.accent : "#f5caca";
  const displayName = (data.display_name || data.username || "User").slice(0, 28);
  const rawBio = (data.bio || "Personal profile on sinss.lol.")
    .replace(/\s+/g, " ")
    .trim();
  const bio = rawBio.length > 165 ? `${rawBio.slice(0, 162).trimEnd()}...` : rawBio;

  const resolvedBadges = badgesForProfile(data as unknown as Profile, [])
    .filter((b) => b && typeof b.name === "string")
    .slice(0, 5)
    .map((b) => b.name.slice(0, 28));

  const uidText = data.public_uid ? `UID #${data.public_uid}` : "sinss.lol";
  const joinedText =
    !data.hide_join_date && data.created_at
      ? `Joined ${new Date(data.created_at).toLocaleDateString("en-US", {
          month: "short",
          year: "numeric",
          timeZone: "UTC",
        })}`
      : "Member on sinss.lol";

  const viewsVal = data.hide_views ? "Hidden" : Number(data.views || 0).toLocaleString("en-US");
  const likesVal = data.hide_likes ? "Hidden" : Number(data.like_count || 0).toLocaleString("en-US");
  const creditsVal = Number(data.credits || 0).toLocaleString("en-US");
  const streakNum = Number(data.daily_streak || 0);
  const streakVal = `${streakNum.toLocaleString("en-US")} ${streakNum === 1 ? "Day" : "Days"}`;

  const avatarUrl = isSafeSatoriImageUrl(data.avatar_url) ? data.avatar_url.trim() : null;
  const bgUrl = isSafeSatoriImageUrl(data.background_url) ? data.background_url.trim() : null;

  return new ImageResponse(
    (
      <div
        style={{
          width: "100%",
          height: "100%",
          display: "flex",
          position: "relative",
          background: "#07090e",
          color: "#ffffff",
          fontFamily: "Arial, sans-serif",
          overflow: "hidden",
        }}
      >
        {bgUrl ? (
          <img
            src={bgUrl}
            alt=""
            width={WIDTH}
            height={HEIGHT}
            style={{
              position: "absolute",
              inset: 0,
              width: "100%",
              height: "100%",
              objectFit: "cover",
              opacity: 0.22,
            }}
          />
        ) : null}

        <div
          style={{
            position: "absolute",
            inset: 0,
            display: "flex",
            background: `radial-gradient(circle at 88% 16%, ${accent}33 0%, transparent 45%), radial-gradient(circle at 12% 88%, ${accent}1f 0%, transparent 40%), linear-gradient(135deg, rgba(7,9,14,0.88) 0%, rgba(12,17,26,0.95) 100%)`,
          }}
        />

        <div
          style={{
            position: "relative",
            display: "flex",
            flexDirection: "column",
            justifyContent: "space-between",
            width: "100%",
            height: "100%",
            padding: "28px 36px",
          }}
        >
          {/* Top Bar */}
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", width: "100%" }}>
            <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
              <div style={{ width: 10, height: 28, borderRadius: 6, background: accent, display: "flex" }} />
              <div style={{ fontSize: 24, fontWeight: 800, letterSpacing: "-0.02em", display: "flex" }}>sinss.lol</div>
              <div
                style={{
                  display: "flex",
                  alignItems: "center",
                  padding: "5px 14px",
                  borderRadius: 999,
                  background: "rgba(0, 0, 0, 0.06)",
                  border: "1px solid rgba(0, 0, 0, 0.12)",
                  color: "#7c0c0c",
                  fontSize: 15,
                  fontWeight: 600,
                }}
              >
                sinss.lol/{data.username}
              </div>
            </div>

            <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
              <div
                style={{
                  display: "flex",
                  alignItems: "center",
                  padding: "6px 14px",
                  borderRadius: 999,
                  background: `${accent}1f`,
                  border: `1px solid ${accent}66`,
                  color: accent,
                  fontSize: 15,
                  fontWeight: 700,
                }}
              >
                {uidText}
              </div>
              <div
                style={{
                  display: "flex",
                  alignItems: "center",
                  padding: "6px 14px",
                  borderRadius: 999,
                  background: "rgba(0, 0, 0, 0.05)",
                  border: "1px solid rgba(0, 0, 0, 0.1)",
                  color: "#440e0e",
                  fontSize: 15,
                  fontWeight: 600,
                }}
              >
                {joinedText}
              </div>
            </div>
          </div>

          {/* Center Identity Section */}
          <div
            style={{
              display: "flex",
              alignItems: "center",
              gap: 28,
              padding: "18px 24px",
              borderRadius: 22,
              background: "rgba(0, 0, 0, 0.035)",
              border: "1px solid rgba(0, 0, 0, 0.09)",
              width: "100%",
            }}
          >
            {avatarUrl ? (
              <img
                src={avatarUrl}
                alt=""
                width={136}
                height={136}
                style={{
                  width: 136,
                  height: 136,
                  borderRadius: 68,
                  objectFit: "cover",
                  border: `3px solid ${accent}`,
                }}
              />
            ) : (
              <div
                style={{
                  width: 136,
                  height: 136,
                  borderRadius: 68,
                  border: `3px solid ${accent}`,
                  background: "#121a24",
                  color: accent,
                  fontSize: 54,
                  fontWeight: 800,
                  display: "flex",
                  alignItems: "center",
                  justifyContent: "center",
                }}
              >
                {String(data.username || "U").slice(0, 1).toUpperCase()}
              </div>
            )}

            <div style={{ display: "flex", flexDirection: "column", flex: 1, minWidth: 0 }}>
              <div style={{ display: "flex", alignItems: "baseline", gap: 14 }}>
                <div style={{ fontSize: 42, fontWeight: 800, color: "#000000", lineHeight: 1.1, display: "flex" }}>
                  {displayName}
                </div>
                <div style={{ fontSize: 22, fontWeight: 700, color: accent, display: "flex" }}>
                  @{data.username}
                </div>
              </div>

              <div
                style={{
                  fontSize: 19,
                  color: "#550c0c",
                  marginTop: 8,
                  lineHeight: 1.35,
                  display: "flex",
                }}
              >
                {bio}
              </div>

              {resolvedBadges.length > 0 ? (
                <div style={{ display: "flex", alignItems: "center", gap: 8, marginTop: 14, flexWrap: "wrap" }}>
                  {resolvedBadges.map((badgeName) => (
                    <div
                      key={badgeName}
                      style={{
                        display: "flex",
                        alignItems: "center",
                        padding: "4px 12px",
                        borderRadius: 999,
                        background: "rgba(0, 0, 0, 0.06)",
                        border: `1px solid ${accent}55`,
                        color: "#f71010",
                        fontSize: 14,
                        fontWeight: 700,
                      }}
                    >
                      {badgeName}
                    </div>
                  ))}
                </div>
              ) : null}
            </div>
          </div>

          {/* Bottom Stat Grid */}
          <div style={{ display: "flex", alignItems: "stretch", gap: 14, width: "100%" }}>
            {[
              { label: "Profile Views", value: viewsVal },
              { label: "Profile Likes", value: likesVal },
              { label: "Sinss Credits", value: creditsVal },
              { label: "Daily Streak", value: streakVal },
            ].map((stat) => (
              <div
                key={stat.label}
                style={{
                  display: "flex",
                  flexDirection: "column",
                  justifyContent: "center",
                  flex: 1,
                  padding: "12px 18px",
                  borderRadius: 16,
                  background: "rgba(0, 0, 0, 0.04)",
                  border: "1px solid rgba(0, 0, 0, 0.08)",
                }}
              >
                <div style={{ fontSize: 13, fontWeight: 600, color: "#3e0f0f", display: "flex" }}>
                  {stat.label}
                </div>
                <div style={{ fontSize: 24, fontWeight: 800, color: "#ffffff", marginTop: 4, display: "flex" }}>
                  {stat.value}
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    ),
    {
      width: WIDTH,
      height: HEIGHT,
      headers: {
        "Cache-Control": "no-store, max-age=0",
      },
    }
  );
}
