import type { Metadata, Viewport } from "next";
import { redirect } from "next/navigation";
import { createClient } from "@/lib/supabase/server";
import { SITE_NAME } from "@/lib/constants";
import ClaimForm from "./ClaimForm";

export const dynamic = "force-dynamic";

export async function generateMetadata({
  searchParams,
}: {
  searchParams?: Promise<{ handle?: string; username?: string; ref?: string; code?: string }>;
}): Promise<Metadata> {
  const sp = searchParams ? await searchParams : {};
  const ref = (sp.ref || sp.code || "").trim().toUpperCase();
  const handle = (sp.handle || sp.username || "").toLowerCase().trim();

  if (ref) {
    return {
      title: `Claim Your Handle · 3-Day Premium Trial Included | ${SITE_NAME}`,
      description: `Claim your custom username on ${SITE_NAME} using creator code ${ref} to unlock 3 days of Premium and an exclusive supporter badge.`,
      openGraph: {
        title: `Claim Your Handle · 3-Day Premium Trial Included | ${SITE_NAME}`,
        description: `Claim your custom username on ${SITE_NAME} using creator code ${ref} to unlock 3 days of Premium and an exclusive supporter badge.`,
      },
      twitter: {
        card: "summary_large_image",
        title: `Claim Your Handle · 3-Day Premium Trial Included | ${SITE_NAME}`,
        description: `Claim your custom username on ${SITE_NAME} using creator code ${ref} to unlock 3 days of Premium and an exclusive supporter badge.`,
      },
    };
  }

  if (handle) {
    return {
      title: `Claim @${handle} | ${SITE_NAME}`,
      description: `Reserve your custom bio link @${handle} on ${SITE_NAME}. Free forever, live in seconds.`,
    };
  }

  return {
    title: `Claim Your Username | ${SITE_NAME}`,
    description: `Reserve your personal bio link handle on ${SITE_NAME} for your links, music, Discord presence, and socials.`,
  };
}

export const viewport: Viewport = {
  themeColor: "#f8e3e3",
};

export default async function ClaimPage({
  searchParams,
}: {
  searchParams?: Promise<{ handle?: string; username?: string; ref?: string; code?: string }>;
}) {
  const sp = searchParams ? await searchParams : {};
  const queryHandle = (sp.handle || sp.username || "")
    .toLowerCase()
    .replace(/[^a-z0-9_]/g, "")
    .slice(0, 20);
  const queryRef = (sp.ref || sp.code || "")
    .toUpperCase()
    .replace(/[^A-Z0-9_]/g, "")
    .slice(0, 20);

  const supabase = await createClient();
  const {
    data: { user },
  } = await supabase.auth.getUser();

  if (!user) {
    const params = new URLSearchParams();
    if (queryHandle) params.set("handle", queryHandle);
    if (queryRef) params.set("ref", queryRef);
    const qs = params.toString();
    const returnTarget = qs ? `/claim?${qs}` : "/claim";

    const signupParams = new URLSearchParams({ next: returnTarget });
    if (queryHandle) signupParams.set("username", queryHandle);
    if (queryRef) signupParams.set("ref", queryRef);

    redirect(`/signup?${signupParams.toString()}`);
  }

  const { data: existing } = await supabase
    .from("profiles")
    .select("username")
    .eq("id", user.id)
    .maybeSingle();

  if (existing) {
    redirect("/dashboard");
  }

  // Suggest requested handle first, or Discord handle fallback
  const suggested =
    queryHandle ||
    (user.user_metadata?.preferred_username || user.user_metadata?.name || "")
      .toLowerCase()
      .replace(/[^a-z0-9_]/g, "")
      .slice(0, 20);

  return <ClaimForm suggested={suggested} />;
}
