import { CustomMDX } from "@/app/components/mdx-components";
import { Metadata } from "next";
import { generateEmbed } from "@/app/common/embed";
import { Title } from "@/app/components/title";
import { getDocContent, getDocsContent, getDocsDirectories, getMetadata } from "@/app/common/documentation";
import {
  Breadcrumb,
  BreadcrumbItem,
  BreadcrumbLink,
  BreadcrumbList,
  BreadcrumbPage,
  BreadcrumbSeparator,
} from "@/app/components/ui/breadcrumb";
import { capitalizeFirstLetter } from "@/app/common/string-utils";

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

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

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

export async function generateMetadata({ params: { slug } }: DocumentationPageParams): Promise<Metadata> {
  const page = getDocContent(slug);

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

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

export default function Page({ params: { slug } }: DocumentationPageParams) {
  const page = getDocContent(slug);

  // 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>
    );
  }

  const slugParts = page.slug.split("/");

  return (
    <div className="w-full px-4 flex flex-col gap-4">
      {slugParts.length > 1 && (
        <Breadcrumb>
          <BreadcrumbList>
            <BreadcrumbItem>
              <BreadcrumbLink href="/docs">Home</BreadcrumbLink>
            </BreadcrumbItem>
            {slugParts.map((slug, index, array) => {
              const path = array.slice(0, index + 1).join("/");

              return (
                <div key={slug} className="flex items-center ">
                  <BreadcrumbSeparator className="px-1.5" />
                  <BreadcrumbItem>
                    <BreadcrumbLink href={`/docs/${path}`}>{capitalizeFirstLetter(slug)}</BreadcrumbLink>
                  </BreadcrumbItem>
                </div>
              );
            })}
          </BreadcrumbList>
        </Breadcrumb>
      )}

      {/* The documentation page title and description */}
      <div className="text-center mb-4">
        <Title title={page.title} subtitle={page.summary} />
      </div>

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