import { notFound } from "next/navigation";
import type { Metadata } from "next";
import { createHash } from "crypto";
import { createAdminClient } from "@/lib/supabase/admin";
import ProfilePage from "@/components/ProfilePage";
import { normalizeUsernameRouteParam, SITE_NAME, type Profile } from "@/lib/constants";
import { getSiteUrl } from "@/lib/site-url";
import { isAccountRestricted } from "@/lib/moderation";
import Link from "next/link";
import CommentsSection from "@/components/CommentsSection";
import ProfileScrollNav from "@/components/ProfileScrollNav";
import ThemeToggle from "@/components/ThemeToggle";
import GuestSignupBanner from "@/components/GuestSignupBanner";
import { scrollLayoutShowsHeroHint } from "@/lib/profile-sections";

export const revalidate = 30;

const PUBLIC_PROFILE_COLUMNS: (keyof Profile)[] = [
  "id", "username", "display_name", "bio", "accent", "bg", "avatar_url", "background_url", "audio_url",
  "audio_tracks", "audio_shuffle", "audio_player_enabled", "click_sound_url", "effect", "cursor_effect", "custom_cursor_url",
  "enter_text", "enter_text_effect", "enter_text_color", "enter_text_size", "links", "views",
  "like_count", "created_at", "public_uid", "layout", "discord_id", "discord_enabled", "discord_invite_url",
  "discord_premium_type", "github_user", "timezone", "hide_timezone", "skills", "modules", "alias", "hide_alias", "hide_username",
  "badges", "admin_badge_ids", "text_color", "icon_color", "link_color", "background_color", "primary_color", "secondary_color",
  "background_effect_color", "profile_opacity", "profile_blur", "profile_card_width", "profile_card_radius",
  "profile_card_border_color", "profile_card_border_width", "avatar_shape", "location", "pronouns", "font",
  "profile_animation", "cursor_follow_intensity", "background_effect", "username_effect", "profile_gradient",
  "monochrome_icons", "animated_title", "use_discord_avatar", "swap_box_colors", "discord_avatar_decoration",
  "badges_glow", "hide_views", "hide_bookmarks", "hide_likes", "hide_join_date", "search_indexing",
  "website_title", "website_description", "website_image_url", "favicon_url", "add_user_info_overlay",
  "comments_enabled", "pinned_comment_id", "about_me", "scroll_enabled", "embed_preset", "referral_code",
  "link_clicks", "tos_accepted_at", "onboarding_dismissed", "premium_until",
  "moderation_status", "suspended_until", "moderation_reason",
  "credits", "avatar_frame", "card_frame", "avatar_decoration", "link_style",
  "is_promoter", "promoter_verified_at", "hide_promoter_aura", "is_creator",
];

import { cache } from "react";

const getProfile = cache(async (usernameOrAlias: string) => {
  const supabase = createAdminClient();
  const key = normalizeUsernameRouteParam(usernameOrAlias);
  let columns = [...PUBLIC_PROFILE_COLUMNS];
  const lookup = async (selectedColumns: typeof columns) => {
    const byEither = await supabase
      .from("profiles")
      .select(selectedColumns.join(","))
      .or(`username.eq.${key},alias.eq.${key}`)
      .limit(1)
      .maybeSingle();
    if (byEither.data || byEither.error) return byEither;

    return supabase
      .from("profiles")
      .select(selectedColumns.join(","))
      .eq("username", key)
      .maybeSingle();
  };
  let { data, error } = await lookup(columns);

  while (error) {
    const missingOptionalColumn = (["admin_badge_ids", "hide_bookmarks", "click_sound_url", "credits", "avatar_frame", "card_frame", "avatar_decoration", "link_style"] as const)
      .find((column) => columns.includes(column) && error.message.includes(column));
    if (!missingOptionalColumn) break;

    columns = columns.filter((column) => column !== missingOptionalColumn);
    const fallback = await lookup(columns);
    data = fallback.data;
    error = fallback.error;
  }

  if (error) {
    console.error("Public profile lookup failed:", error);
    throw new Error("Could not load this profile. Please try again later.");
  }

  return data as unknown as Profile | null;
});

export async function generateMetadata({ params }: { params: Promise<{ username: string }> }): Promise<Metadata> {
  const username = normalizeUsernameRouteParam((await params).username);
  const profile = await getProfile(username);
  if (!profile) return { title: "Not found" };
  if (isAccountRestricted(profile.moderation_status, profile.suspended_until)) {
    const label = profile.moderation_status === "banned" ? "Profile banned" : "Profile suspended";
    return {
      title: `${label} | ${SITE_NAME}`,
      description: "This profile is currently unavailable.",
      robots: { index: false, follow: false },
    };
  }
  const title = profile.website_title || profile.display_name || profile.username;
  const description = profile.website_description || profile.bio || `@${profile.username} on ${SITE_NAME}`;
  let image: string;
  if (profile.website_image_url && profile.add_user_info_overlay === false) {
    image = profile.website_image_url;
  } else {
    const imageUrl = new URL(`/${encodeURIComponent(username)}/opengraph-image`, getSiteUrl());
    const previewVersion = createHash("sha256")
      .update(
        JSON.stringify([
          title,
          description,
          profile.avatar_url,
          profile.website_image_url,
          profile.accent,
          profile.embed_preset,
          profile.add_user_info_overlay,
        ])
      )
      .digest("hex")
      .slice(0, 12);
    imageUrl.searchParams.set("v", previewVersion);
    image = imageUrl.toString();
  }
  const favicon = profile.favicon_url || "/sinss-mark.svg";
  return {
    title: `${title} | ${SITE_NAME}`,
    description,
    icons: { icon: favicon, shortcut: favicon, apple: favicon },
    alternates: { canonical: `/${encodeURIComponent(username)}` },
    openGraph: {
      title: `${title} | ${SITE_NAME}`,
      description,
      images: [{ url: image, width: 1200, height: 630, alt: `${title} on ${SITE_NAME}` }],
    },
    twitter: {
      card: "summary_large_image",
      title: `${title} | ${SITE_NAME}`,
      description,
      images: [image],
    },
    robots: profile.search_indexing === false ? { index: false, follow: false } : undefined,
  };
}

export default async function PublicProfile({
  params,
  searchParams,
}: {
  params: Promise<{ username: string }>;
  searchParams: Promise<{ templatePreview?: string }>;
}) {
  const username = normalizeUsernameRouteParam((await params).username);
  const profile = await getProfile(username);
  if (!profile) notFound();

  if (isAccountRestricted(profile.moderation_status, profile.suspended_until)) {
    const status = profile.moderation_status;
    const banned = status === "banned" || status === "blacklisted";
    const expiry = banned
      ? "Permanent"
      : profile.suspended_until
        ? new Date(profile.suspended_until).toLocaleString()
        : "Until further notice";
    const statusLabel = status === "blacklisted" ? "Blacklisted" : status === "banned" ? "Banned" : "Suspended";
    const headingText = status === "blacklisted" ? "This user is blacklisted" : status === "banned" ? "This user is banned" : "This user is suspended";
    const reason = profile.moderation_reason ?? null;

    return (
      <main style={{ minHeight: "100vh", display: "grid", placeItems: "center", padding: 24, background: "radial-gradient(circle at 50% 0%, rgba(245, 202, 202, .12), #07090c 52%)", color: "#db0606" }}>
        <section role="status" style={{ width: "min(460px,100%)", border: "1px solid #372525", borderRadius: 12, background: "rgba(13,18,22,.96)", padding: "28px clamp(20px,6vw,36px)", boxShadow: "0 22px 70px rgba(0,0,0,.42)" }}>
          <p style={{ margin: "0 0 8px", color: banned ? "#ffffff" : "#f1adad", fontSize: 11, fontWeight: 800, letterSpacing: ".08em", textTransform: "uppercase" }}>Profile unavailable</p>
          <h1 style={{ margin: "0 0 20px", fontSize: 27, lineHeight: 1.2 }}>{headingText}</h1>
          <dl style={{ display: "grid", gridTemplateColumns: "90px minmax(0,1fr)", gap: "10px 16px", margin: 0, padding: "16px 0", borderTop: "1px solid #3a2828", borderBottom: "1px solid #3a2828" }}>
            <dt style={{ color: "#300b0b", fontSize: 12 }}>Status</dt>
            <dd style={{ margin: 0, fontSize: 13 }}>{statusLabel}</dd>
            <dt style={{ color: "#300b0b", fontSize: 12 }}>Duration</dt>
            <dd style={{ margin: 0, fontSize: 13 }}>{expiry}</dd>
            {reason && (
              <>
                <dt style={{ color: "#300b0b", fontSize: 12 }}>Reason</dt>
                <dd style={{ margin: 0, fontSize: 13, color: "#610909" }}>{reason}</dd>
              </>
            )}
          </dl>
          <p style={{ margin: "14px 0 0", color: "#370a0a", fontSize: 13 }}>For questions about this restriction, contact the site owner on Discord.</p>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10, marginTop: 20 }}>
            <Link href="/" style={{ minHeight: 42, display: "grid", placeItems: "center", border: "1px solid #352020", borderRadius: 7, color: "#670808", textDecoration: "none", fontSize: 13, fontWeight: 700 }}>Back to home</Link>
            <Link href="/dashboard" style={{ minHeight: 42, display: "grid", placeItems: "center", borderRadius: 7, background: "#f5caca", color: "#061014", textDecoration: "none", fontSize: 13, fontWeight: 800 }}>Back to dashboard</Link>
          </div>
        </section>
      </main>
    );
  }

  const { templatePreview: templatePreviewId } = await searchParams;
  let previewMode = false;
  let profileWithPreview = profile;
  if (templatePreviewId) {
    const supabase = createAdminClient();
    const { data: template, error } = await supabase
      .from("profile_templates")
      .select("data")
      .eq("id", templatePreviewId)
      .eq("is_public", true)
      .maybeSingle();
    if (error) {
      console.error("Template preview lookup failed:", error);
      throw new Error("Could not load this template preview. Please try again later.");
    }
    if (!template || typeof template.data !== "object" || template.data === null || Array.isArray(template.data)) notFound();

    const previewKeys: (keyof Profile)[] = [
      "accent", "bg", "avatar_url", "avatar_shape", "background_url", "background_color", "profile_gradient",
      "audio_url", "audio_tracks", "audio_shuffle", "audio_player_enabled", "enter_text", "enter_text_effect",
      "enter_text_color", "enter_text_size", "profile_opacity", "profile_blur", "profile_card_width",
      "profile_card_radius", "profile_card_border_color", "profile_card_border_width", "layout", "modules",
      "text_color", "icon_color", "link_color", "monochrome_icons", "animated_title", "badges_glow",
      "username_effect", "background_effect", "background_effect_color", "effect", "cursor_effect",
      "custom_cursor_url", "font", "profile_animation", "cursor_follow_intensity", "primary_color",
      "secondary_color", "swap_box_colors",
    ];
    const safeTemplateData: Partial<Profile> = {};
    for (const key of previewKeys) {
      const value = (template.data as Partial<Profile>)[key];
      if (value !== undefined) Object.assign(safeTemplateData, { [key]: value });
    }
    profileWithPreview = { ...profile, ...safeTemplateData };
    previewMode = true;
  }

  const publicProfile = { ...profileWithPreview };
  delete publicProfile.moderation_status;
  delete publicProfile.suspended_until;
  delete publicProfile.moderation_reason;
  delete publicProfile.moderated_at;
  delete publicProfile.moderated_by;
  delete publicProfile.id;
  delete publicProfile.aliases;
  delete publicProfile.username_changed_at;
  if (publicProfile.hide_alias) publicProfile.alias = "";
  if (publicProfile.hide_views) publicProfile.views = 0;
  if (publicProfile.hide_bookmarks || publicProfile.hide_likes) {
    publicProfile.like_count = 0;
    publicProfile.bookmark_count = 0;
  }
  if (publicProfile.hide_join_date) publicProfile.created_at = "";
  if (publicProfile.hide_timezone) publicProfile.timezone = "";

  const hasAboutSection = Boolean(publicProfile.scroll_enabled && publicProfile.about_me);
  const hasCommentsSection = publicProfile.comments_enabled !== false;
  const onMediaBackdrop = publicProfile.layout === "scroll";
  const sectionClass = onMediaBackdrop ? "pfSection pfOnMedia" : "pfSection";
  const aboutSubtitleSource = (publicProfile.website_description || publicProfile.bio || "").trim();
  const aboutSubtitle = aboutSubtitleSource ? aboutSubtitleSource.split("\n")[0].trim().slice(0, 140) : "";
  const showPageHint = !scrollLayoutShowsHeroHint(publicProfile);

  return (
    <>
      <ThemeToggle />
      <ProfilePage profile={publicProfile} previewMode={previewMode} />
      <GuestSignupBanner profileUsername={publicProfile.username} accent={publicProfile.accent} />
      {hasAboutSection ? (
        <section id="about-me" className={sectionClass} style={{ marginBottom: hasCommentsSection ? undefined : 96 }}>
          <h2 className="pfSectionTitle">Learn about me</h2>
          {aboutSubtitle ? <p className="pfSectionSub">{aboutSubtitle}</p> : null}
          <div className="pfCard">
            <p className="pfCardText">{publicProfile.about_me}</p>
          </div>
        </section>
      ) : null}
      {hasCommentsSection ? (
        <CommentsSection username={publicProfile.username} accent={publicProfile.accent} onMedia={onMediaBackdrop} />
      ) : null}
      {hasAboutSection || hasCommentsSection ? (
        <ProfileScrollNav hasAbout={hasAboutSection} hasComments={hasCommentsSection} showHint={showPageHint} />
      ) : null}
    </>
  );
}
