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

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

export const metadata: Metadata = {
  title: 'All posts'
}

export default async function Index() {
  const slugs = await getPostSlugs()
  const posts = await Promise.all(slugs.map(loadSinglePage))

  const sortedPosts =
    posts
      .filter((post) => post !== null)
      .filter((post) => !post?.unlisted)
      .sort((a: Post, b: Post) => b.date.valueOf() - a.date.valueOf())

  return (
    <>
      <h1>All posts</h1>
      {sortedPosts.map((post: Post, i: number) => (
        <>
          {i >= 1 && sortedPosts[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>
        </>
      ))}
    </>
  );
}
