import Head from "next/head"
import type { GetStaticPropsResult, GetStaticPathsResult, GetStaticPropsContext } from 'next'
import { Post, SerializablePost, getPostSlugs, loadSinglePage } from "~/utils/post"
import Markdown from 'markdown-to-jsx'

import styles from "~/styles/post.module.css"

interface PageProps {
  post: SerializablePost
}

export async function getStaticPaths(): Promise<GetStaticPathsResult> {
  const slugs = await getPostSlugs()
  return {
    paths: slugs.map((slug: string) => ({
      params: {
        slug
      }
    })),
    fallback: false
  }
}

export async function getStaticProps({ params: { slug } }: GetStaticPropsContext): Promise<GetStaticPropsResult<PageProps>> {
  if (Array.isArray(slug))
    throw new Error('Could not generate page for: ' + slug.join(','))

  const post = await loadSinglePage(slug)

  if (!post)
    throw new Error('Could not find page: ' + slug)

  return {
    props: { post: { ...post, date: post.date.toISOString() } }
  }
}

export default function Index({ post: serializedPost }: PageProps) {
  const post = { ...serializedPost, date: new Date(serializedPost.date) }

  return (
    <>
      <Head>
        <title>{post.title}</title>
      </Head>
      <article className={styles.post}>
        <span>{post.date.toLocaleDateString()}</span>
        <h1>{post.title}</h1>
        <p className={styles.subtitle}>{post.subtitle}</p>

        <Markdown>{post.body}</Markdown>
      </article>
    </>
  );
}
