import DetailPageBlog from "@/components/blogs/DetailPageBlog";
import { fetchBlogDetail } from "@/services/payload/blog";
import { getDefaultMetadata } from "@/utils/metadata";
import { Metadata } from "next";
import { headers } from "next/headers";
import { notFound } from "next/navigation";

export async function generateMetadata(props: { params: Promise<{ slug: string }> }): Promise<Metadata> {
  const metadata = await getDefaultMetadata();
  const params = await props.params;

  let title = `Page Not Found - ${metadata.openGraph?.siteName}`;
  let description = title;
  let publishedAt = "";
  let updatedAt = "";
  let imgUrl = "";
  let createdByName = "";
  let canonicalUrl = "";

  const blog = await fetchBlogDetail(params.slug);
  if (!!blog) {
    // check for blog data
    title = `${!!blog.data?.meta?.title ? blog.data?.meta?.title : blog.data.title} - ${metadata.openGraph?.siteName}`;
    description = `${!!blog.data?.meta?.description ? blog.data?.meta?.description : blog.data.title}`;
    imgUrl = blog.img.url;
    publishedAt = blog.data.createdAt;
    updatedAt = blog.data.updatedAt;
    if (!!blog.data?.meta?.canonical_url) {
      canonicalUrl = blog.data.meta.canonical_url;
    }
    if (!!blog?.data?.createdBy && typeof blog.data.createdBy !== "number") {
      createdByName = blog.data.createdBy?.name ?? "";
    }
  }

  metadata.title = title;
  metadata.description = description;
  if (!!metadata.openGraph) {
    // @ts-ignore
    metadata.openGraph.type = "article";
    metadata.openGraph.title = title;
    metadata.openGraph.description = description;
    metadata.openGraph.images = !!imgUrl ? [imgUrl] : undefined;
  }
  if (!!metadata.alternates && !!canonicalUrl) {
    metadata.alternates.canonical = canonicalUrl;
  }
  metadata.twitter = {
    card: "summary_large_image",
    title: title,
    description: description,
    images: !!imgUrl ? [imgUrl] : undefined,
  };
  metadata.other = {
    "article:published_time": publishedAt,
    "article:modified_time": updatedAt,
    "twitter:label1": "Written by",
    "twitter:data1": !!createdByName ? createdByName : "Admin",
    "twitter:label2": "Est. reading time",
    "twitter:data2": "3 minutes",
  };

  return metadata;
}

export default async function BlogDetail(props: { params: Promise<{ slug: string }> }) {
  const params = await props.params;
  const headersList = await headers();
  const fullUrl = headersList.get("x-full-url");
  const blog = await fetchBlogDetail(params.slug);
  if (!blog) return notFound();

  const shareUrl = {
    facebook: `https://www.facebook.com/sharer/sharer.php?u=${fullUrl}`,
    linkedin: `https://www.linkedin.com/sharing/share-offsite/?url=${fullUrl}`,
    twitter: `https://twitter.com/intent/tweet?url=${fullUrl}`,
  };

  return (
    <>
      <DetailPageBlog data={blog} shareUrl={shareUrl} />
    </>
  );
}
