import DefaultLayout from '@/layouts/DefaultLayout/DefaultLayout'
import { getContentTags, getStaticEntries } from '@/lib/content'
import { NextSeo } from 'next-seo'
import Link from 'next/link'

export const getStaticProps = () => ({
  props: {
    tags: getContentTags('./content/writing'),
    postEntries: getStaticEntries('./content/writing')
  }
})

export const Title = 'Tags'

export default function Tags ({ tags, postEntries }) {
  const tagNames = Object.keys(tags).sort()

  return (
    <DefaultLayout>
      <NextSeo
        title={Title}
        openGraph={
          {
            title: Title
          }
        }
      />

      <h1>{Title}</h1>

      <section>

        <table>
          <thead>
            <tr>
              <th>Tag</th>
              <th>Posts</th>
            </tr>

          </thead>
          <tbody>
            {tagNames.map(tag => {
              const posts = postEntries.filter(p => p.attributes.tags.includes(tag)).sort((a, b) => a.attributes.title > b.attributes.title ? 1 : -1)

              return (
                <tr key={tag}>
                  <td>{tag} ({posts.length})</td>
                  <td>
                    {posts && posts.map(post => {
                      return (
                        <div key={'tag-' + post.slug}><Link href={`/writing/${post.slug}`}>{post.attributes.title}</Link></div>
                      )
                    })}
                  </td>
                </tr>
              )
            })}
          </tbody>
        </table>
      </section>
    </DefaultLayout>
  )
}
