import { appConfig } from "@/config/app"
import DetailExperienceKuisineContainer from "./section/DetailExperienceKuisineContainer"
import { revalidatePath } from "next/cache"
import { notFound } from "next/navigation"
import { cookies, headers } from "next/headers"

type Props = { params: { postid: string } }

const fetchKuisineDetail: any = async (id: string, accessToken: string) => {
  try {
    const res = await fetch(`${appConfig.apiUrl}/kuisines/mine/experiences/${id}`, {
      method: "GET",
      headers: {
        "Content-Type": "application/json",
        Origin: appConfig.appUrl,
        Authorization: "Bearer " + accessToken,
      },
      next: { revalidate: 0 },
    })
    if (!res.ok) throw new Error("Failed to fetch Kuisine Experiences data")
    return res.json()
  } catch (error) {
    console.error("Error fetching Kuisine Experiences data:", error)
    return null
  }
}

export async function generateMetadata(props: Props) {
  const { postid } = props.params
  const accessToken =
    headers()
      .get("cookie")
      ?.split("; ")
      .find((c) => c.startsWith("access_token="))
      ?.split("=")[1] || ""
  const kuisine = await fetchKuisineDetail(postid, accessToken)

  if (!kuisine)
    return {
      title: "404 - Page Not Found",
      description: "The page you are looking for does not exist. Please return to the homepage.",
    }

  return {
    title: kuisine?.eventhost || "Update Experience",
    description: kuisine?.eventtype || "",
    alternates: {
      canonical: `${appConfig.appUrl}/kuisine/update-experience/${postid}`,
    },
    keywords: "",
    robots: "index, follow",
    openGraph: {
      title: kuisine?.eventhost || "Update Experience",
      description: kuisine?.eventtype || "",
      url: `${appConfig.apiUrl}/kuisine/update-experience/${postid}`,
      siteName: "WIZZOR",
      images: [
        {
          url: kuisine?.thumbnail ? kuisine?.thumbnail : `${appConfig.appUrl}/wizzor_group_2x.png`,
          width: 960,
          height: 630,
          alt: "Kuisine",
        },
      ],
      type: "website",
    },
    twitter: {
      title: kuisine?.eventhost || "Update Experience",
      description: kuisine?.eventtype || "",
      images: [kuisine?.thumbnail ? kuisine?.thumbnail : `${appConfig.appUrl}/wizzor_group_2x.png`],
      site: "WIZZOR",
    },
  }
}

const revalidate = async (id: number | string) => {
  "use server"
  revalidatePath(`${appConfig.apiUrl}/kuisines/mine/experiences/${id}`)
}

export default async function DetailExperienceKuisinePage(props: Props) {
  const accessToken = cookies().get("access_token")?.value
  const { postid } = props.params

  const kuisine = await fetchKuisineDetail(postid, accessToken)

  if (!kuisine) notFound()

  return (
    <DetailExperienceKuisineContainer
      kuisineDetail={kuisine?.data || {}}
      revalidate={revalidate}
    />
  )
}
