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;
  imagePosition?: "left" | "right";
  link?: ComponentType<LinkProps>;
  description?: string;
}

export function createReadAllPage({
  title,
  image,
  pagePath,
  link,
  description,
  imagePosition,
}: 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}
        description={description}
        imagePosition={imagePosition}
      >
        <OrganizedContent
          id={readAllSection.section.id}
          sections={[
            readAllSection.section,
            ...sections.map(({ section }) => section),
          ]}
          link={Link}
        >
          <readAllSection.Content />
        </OrganizedContent>
      </Header>
    );
  };
}
