import { getRegistrationInvoiceAction } from "../../../lib/actions/registrationInvoiceAction";
import { getRegisterDetailsAction } from "../../../lib/actions/registerDetailsAction";
import { fetchHeaderFooterForLayout } from "../../../lib/serverFetch";
import { getThankYouPageDataAction } from "../../../lib/actions/thankYouPageAction";
import ThankYouClient from "./ThankYouClient";

export const dynamic = "force-dynamic";

interface PageProps {
  params: Promise<{ id: string }>;
  searchParams: Promise<{ 
    paylater?: string;
    redirect_status?: string;
    payment_intent?: string;
    payment_intent_client_secret?: string;
    setup_intent?: string;
    setup_intent_client_secret?: string;
    lang?: string;
    language?: string;
  }>;
}

export default async function ThankYouPage({ params, searchParams }: PageProps) {
  const { id } = await params;
  const resolvedSearchParams = await searchParams;
  const { 
    paylater, 
    redirect_status, 
    payment_intent, 
    payment_intent_client_secret,
    setup_intent,
    setup_intent_client_secret
  } = resolvedSearchParams;
  const isPayLater = paylater === "true";
  
  // Fetch data from backend
  let invoiceData = null;
  let registerDetails = null;
  let thankYouPageData = null;

  if (isPayLater) {
    registerDetails = await getRegisterDetailsAction(id);
  } else {
    invoiceData = await getRegistrationInvoiceAction(id);
    // Fallback for workshops or cases where no payment invoice exists
    if (!invoiceData || !invoiceData.status) {
      registerDetails = await getRegisterDetailsAction(id);
    }
  }
  
  const lang = resolvedSearchParams.lang || resolvedSearchParams.language || "default";
  const franchiseeId = (resolvedSearchParams as any).franchiseeId as string;
  
  // Fetch footer data & thank-you page content concurrently
  let footerData = null;
  try {
    const [footerResponse, thankYouResponse] = await Promise.all([
      fetchHeaderFooterForLayout(),
      getThankYouPageDataAction(franchiseeId, lang).catch((e: unknown) => {
        return null;
      }),
    ]);
    footerData = footerResponse;
    thankYouPageData = thankYouResponse?.success ? thankYouResponse.data : null;
  } catch (error) {
  }

  return (
    <ThankYouClient 
      invoiceData={invoiceData} 
      registerDetails={registerDetails}
      paylater={isPayLater}
      footerData={footerData}
      thankYouPageData={thankYouPageData}
      registrationId={id}
      redirectStatus={redirect_status}
      paymentIntent={payment_intent}
      paymentIntentClientSecret={payment_intent_client_secret}
      setupIntent={setup_intent}
      setupIntentClientSecret={setup_intent_client_secret}
    />
  );
}
