import Head from "next/head"
import Link from 'next/link'
import { Post, SerializablePost, getPostSlugs, loadSinglePage } from "~/utils/post"

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

interface PageProps {
  sortedPosts: SerializablePost[]
}

export async function getStaticProps(): Promise<{ props: PageProps }> {
  const slugs = await getPostSlugs()
  const posts = await Promise.all(slugs.map(loadSinglePage))

  const sortedPosts =
    posts
      .sort((a: Post, b: Post) => b.date.valueOf() - a.date.valueOf())
      .map((post: Post): SerializablePost => ({ ...post, date: post.date.toISOString() }))

  return {
    props: { sortedPosts }
  }
}

export default function Index({ sortedPosts }: PageProps) {
  const deserializedPosts = sortedPosts.map((post: SerializablePost): Post => ({ ...post, date: new Date(post.date) }))

  return (
    <>
      <Head>
        <title>All posts</title>
      </Head>
      <h1>All posts</h1>
      {deserializedPosts.map((post: Post, i: number) => (
        <>
          {i >= 1 && deserializedPosts[i - 1].date.getFullYear() != post.date.getFullYear() && (
            <p className={styles.yearSeparator}>{post.date.getFullYear()}</p>
          )}
          <div className={styles.postLink}>
            <h2><Link href={`/${post.slug}`}>{post.title}</Link></h2>
            <span>{post.date.toLocaleDateString()}</span>
            <p>{post.subtitle}</p>
          </div>
        </>
      ))}
    </>
  );
}
