import { getDocumentation } from "@/app/common/documentation";
import { CustomMDX } from "@/app/components/mdx-components";
import { Metadata } from "next";
import { generateEmbed } from "@/app/common/embed";

type DocumentationPageParams = {
  params: {
    slug?: string[];
  };
};

export async function generateStaticParams() {
  let documentationPages = getDocumentation();

  return documentationPages.map(page => ({
    slug: [page.slug],
  }));
}

export async function generateMetadata({ params: { slug } }: DocumentationPageParams): Promise<Metadata> {
  const pageSlug = slug?.join("/");
  const documentationPages = getDocumentation();
  let page = documentationPages.find(page => page.slug === pageSlug);

  // Use the landing page on "/documentation"
  if (!page && !slug) {
    page = documentationPages.find(page => page.slug === "landing");
  }

  // Fallback to page not found
  if (!page) {
    return generateEmbed({
      title: "Page not found",
      description: "The documentation page was not found",
    });
  }

  return generateEmbed({
    title: page.metadata.title,
    description: `${page.metadata.description}\n\nClick to view this page`,
  });
}

export default function Page({ params: { slug } }: DocumentationPageParams) {
  const pageSlug = slug?.join("/");
  const documentationPages = getDocumentation();
  let page = documentationPages.find(page => page.slug === pageSlug);

  // Use the landing page on "/documentation"
  if (!page && !slug) {
    page = documentationPages.find(page => page.slug === "landing");
  }

  // Page was not found, show an error page
  if (!page) {
    return (
      <div className="text-center flex flex-col gap-2">
        <h1 className="text-red-400 text-2xl">Not Found</h1>
        <p>The page you are looking for was not found.</p>
      </div>
    );
  }

  return (
    <div className="w-full px-4 flex flex-col gap-4">
      {/* The documentation page title and description */}
      <div className="text-center mb-4">
        {page.metadata.title && <h1 className="text-2xl">{page.metadata.title}</h1>}
        {page.metadata.description && <h1>{page.metadata.description}</h1>}
      </div>

      {/* The content of the documentation page */}
      <div className="text-left w-full">
        <CustomMDX source={page.content} />
      </div>
    </div>
  );
}
