import { redirect } from "next/navigation";
import { Metadata } from "next";

import BlockedSignupCampaign from "@/components/pages/participant/campaigns/blocked-signup";
import CampaignSignupScreen from "@/components/pages/participant/campaigns/signup-screen";
import { ALLOWED_COUNTRY_CALLING_CODES } from "@/constants/allowed-countries";
import { WORLD_COUNTRY_LIST } from "@/constants/countries";
import { INTERNAL_PAGES } from "@/constants/pages-mapping/internal-pages-mapping";
import {
  getCampaignUserSession,
  getLinkedInCallbackData,
} from "@/lib/campaigns-session";

export const metadata: Metadata = {
  title: "Create a new account | Campaign",
  description:
    "Join industry leaders testing new products and driving strategic decisions. Get paid to share your expertise and gain exclusive early access to innovations.",
};

export default async function SignupPage({
  params,
  searchParams,
}: {
  params: { slug: string };
  searchParams: Record<string, string>;
}) {
  const { countryCode, expired, notFound } = searchParams;
  const isAllowedToSignup = ALLOWED_COUNTRY_CALLING_CODES.some(
    (allowedCountry) => allowedCountry.code === countryCode,
  );
  const countryInfo = WORLD_COUNTRY_LIST.find((x) => x.code === countryCode);
  const countryName = countryInfo?.name || "Unknown";
  const countryCallingCode = countryInfo?.countryCode || "";

  if (!isAllowedToSignup) {
    return <BlockedSignupCampaign countryName={countryName} />;
  }

  const linkedinUser = await getLinkedInCallbackData();
  const { userId } = (await getCampaignUserSession()) || {};

  if (userId) {
    const query = new URLSearchParams(searchParams).toString();
    const target = `${INTERNAL_PAGES.participant.campaign}/${
      params.slug
    }/survey${query ? `?${query}` : ""}`;

    redirect(target);
  }

  const isExpiredOrNotFound = expired === "true" || notFound === "true";

  return (
    <CampaignSignupScreen
      isExpiredOrNotFound={isExpiredOrNotFound}
      linkedinUser={linkedinUser}
      userCountryCode={countryCallingCode}
    />
  );
}
