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

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

const fetchBookDetail: any = async (id: string, accessToken: string) => {
  try {
    const res = await fetch(`${appConfig.apiUrl}/books/${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 book data")
    return res.json()
  } catch (error) {
    console.error("Error fetching book data:", error)
    return null
  }
}

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

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

  return {
    title: book?.title || "Update Book",
    description: book?.subtitle || "",
    alternates: {
      canonical: `${appConfig.appUrl}/books/update-book/${id}`,
    },
    keywords: "",
    robots: "index, follow",
    openGraph: {
      title: book?.title || "Update Book",
      description: book?.subtitle || "",
      url: `${appConfig.apiUrl}/books/update-book/${id}`,
      siteName: "WIZZOR",
      images: [
        {
          url: book?.thumbnail ? book?.thumbnail : `${appConfig.appUrl}/wizzor_group_2x.png`,
          width: 960,
          height: 630,
          alt: "WIZZOR",
        },
      ],
      type: "website",
    },
    twitter: {
      title: book?.title || "Update Book",
      description: book?.subtitle || "",
      images: [book?.thumbnail ? book?.thumbnail : `${appConfig.appUrl}/wizzor_group_2x.png`],
      site: "WIZZOR",
    },
  }
}

export default async function UpdateBookPage(props: Props) {
  const accessToken = cookies().get("access_token")?.value
  const { id } = props.params
  const book = await fetchBookDetail(id, accessToken)

  if (!book) notFound()

  return <UpdateBookContainer book={book} />
}
