import type { Metadata } from "next";
import { Suspense } from "react";
import { PublicProfileSkeleton } from "@/components/profile/PublicProfileSkeleton";
import { PublicProfileView } from "@/components/profile/PublicProfileView";

type SearchParams = Promise<{ username?: string | string[] }>;

function readUsername(value: string | string[] | undefined): string {
  if (typeof value === "string") {
    return value.trim();
  }

  if (Array.isArray(value) && typeof value[0] === "string") {
    return value[0].trim();
  }

  return "";
}

async function fetchPublicProfileMeta(username: string): Promise<{
  displayName: string | null;
  bio: string | null;
} | null> {
  const base = process.env.NEXT_PUBLIC_API_URL?.replace(/\/$/, "");

  if (!base || !username) {
    return null;
  }

  try {
    const response = await fetch(`${base}/api/creators/${encodeURIComponent(username)}`, {
      method: "GET",
      headers: {
        Accept: "application/json",
        "X-Requested-With": "XMLHttpRequest",
      },
      cache: "no-store",
    });

    if (!response.ok) {
      return null;
    }

    const payload = (await response.json()) as {
      success?: boolean;
      profile?: { display_name?: string | null; username?: string; bio?: string | null };
    };

    if (payload.success !== true || !payload.profile) {
      return null;
    }

    return {
      displayName: payload.profile.display_name?.trim() || payload.profile.username || null,
      bio: payload.profile.bio?.trim() || null,
    };
  } catch {
    return null;
  }
}

export async function generateMetadata({
  searchParams,
}: {
  searchParams: SearchParams;
}): Promise<Metadata> {
  const params = await searchParams;
  const username = readUsername(params.username);

  if (!username) {
    return {
      title: "Postvertise Creator Profile",
      description: "View Creator profiles on Postvertise.",
    };
  }

  const meta = await fetchPublicProfileMeta(username);

  if (!meta?.displayName) {
    return {
      title: "Postvertise Creator Profile",
      description: "View Creator profiles on Postvertise.",
    };
  }

  return {
    title: `${meta.displayName} | Postvertise`,
    description: meta.bio || `View ${meta.displayName} on Postvertise.`,
  };
}

export default function ProfilePage() {
  return (
    <Suspense fallback={<PublicProfileSkeleton />}>
      <PublicProfileView />
    </Suspense>
  );
}
