import type { Metadata } from "next";
import { cookies } from "next/headers";
import { notFound, redirect } from "next/navigation";
import { getSupabaseClient } from "@/lib/supabase";
import StoreLayout from "@/components/StoreLayout";
import CatalogCheckoutConfirmationClient from "@/components/CatalogCheckoutConfirmationClient";

export const dynamic = "force-dynamic";
export const revalidate = 0;

export async function generateMetadata(props: {
  params: Promise<{ slug: string }>;
}): Promise<Metadata> {
  const params = await props.params;
  const supabase = getSupabaseClient();
  const { data: profile } = await supabase
    .from("profiles")
    .select("catalog_name,store_name")
    .eq("slug", params.slug)
    .maybeSingle();

  const storeName = profile?.catalog_name || profile?.store_name || "Loja";

  return {
    title: { absolute: `Compra confirmada | ${storeName}` },
    description: `Confirmacao da compra na loja ${storeName}.`,
  };
}

export default async function CatalogCheckoutConfirmationPage(props: {
  params: Promise<{ slug: string }>;
  searchParams: Promise<{ orderId?: string; orderNumber?: string }>;
}) {
  const params = await props.params;
  const searchParams = await props.searchParams;
  const slug = params.slug;
  const orderId = String(searchParams?.orderId || "").trim();
  const orderNumber = String(searchParams?.orderNumber || "").trim();

  if (!orderId) {
    redirect(`/${slug}`);
  }

  const cookieStore = await cookies();
  const token = cookieStore.get("ks_client_portal")?.value || "";
  if (!token) {
    redirect(`/${slug}/cliente/login?next=${encodeURIComponent(`/${slug}/checkout/confirmacao?orderId=${orderId}`)}`);
  }

  const supabase = getSupabaseClient();
  const { data: profile, error: profileError } = await supabase
    .from("profiles")
    .select("*")
    .eq("slug", slug)
    .single();

  if (profileError || !profile?.id) {
    notFound();
  }

  const storeName = profile.catalog_name || profile.store_name || "Loja";
  const logoUrl = profile.catalog_logo_url || profile.logo_url || "";
  const primaryColor = profile.primary_color || "#4425A7";
  const headerColor = profile.catalog_header_color || primaryColor;

  return (
    <StoreLayout
      primaryColor={primaryColor}
      whatsappNumber={profile.whatsapp || undefined}
      cartScope={profile.id || slug}
      storeSlug={slug}
      theme={profile.catalog_theme}
    >
      <CatalogCheckoutConfirmationClient
        slug={slug}
        storeName={storeName}
        logoUrl={logoUrl}
        primaryColor={primaryColor}
        headerColor={headerColor}
        orderId={orderId}
        orderNumber={orderNumber}
      />
    </StoreLayout>
  );
}
