import { MDXRemote, MDXRemoteSerializeResult } from "next-mdx-remote";
import React, { ComponentType } from "react";

import {
  createLink,
  createReadAllSection,
  LinkProps,
  OrganizedContent,
} from "@/components/OrganizedContent";

import { Header } from "./Header";

export interface SerializedSection {
  section: {
    id: string;
    title: string;
  };
  content: MDXRemoteSerializeResult;
}

export interface Props {
  sections: SerializedSection[];
}

export interface Options {
  pagePath: string;
  title: string;
  image: string;
  link?: ComponentType<LinkProps>;
}

export function createReadAllPage({ title, image, pagePath, link }: Options) {
  const Link = link ?? createLink(pagePath);

  return function Page({ sections }: Props) {
    const readAllSection = createReadAllSection(
      sections.map(({ section, content }) => ({
        section,
        Content() {
          return <MDXRemote {...content} />;
        },
      })),
      true
    );

    return (
      <Header title={title} image={image}>
        <OrganizedContent
          id={readAllSection.section.id}
          sections={[
            readAllSection.section,
            ...sections.map(({ section }) => section),
          ]}
          link={Link}
        >
          <readAllSection.Content />
        </OrganizedContent>
      </Header>
    );
  };
}
