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

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

import { GetShapesConfig } from "../ShapesBackground";
import { Title } from "../Title";

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

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

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

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

  Page.getShapesConfig = getShapesConfig;

  return Page;
}
