---
import BlogCard from '@/components/BlogCard.astro'
import Breadcrumbs from '@/components/Breadcrumbs.astro'
import PageHead from '@/components/PageHead.astro'
import PaginationComponent from '@/components/ui/pagination'
import { SITE } from '@/consts'
import Layout from '@/layouts/Layout.astro'
import { fetchPostsPage, groupPostsByYear } from '@/lib/data-utils'

// export async function getStaticPaths({
//   paginate,
// }: {
//   paginate: PaginateFunction
// }) {
//   const allPosts = await getAllPosts()
//   return paginate(allPosts, { pageSize: SITE.postsPerPage })
// }
const nowPage = parseInt(
  new URL(Astro.request.url).searchParams.get('p') || '1',
)

// use url param
// const { page } = Astro.para

const postsPage = await fetchPostsPage(nowPage, SITE.postsPerPage)
const page = {
  data: postsPage.posts,
  currentPage: nowPage,
  lastPage: postsPage.totalPages,
}
// fetch page
if (page.lastPage < page.currentPage) {
  console.log('redirect to 404')
  return Astro.rewrite('/404')
}
const postsByYear = groupPostsByYear(page.data)
const years = Object.keys(postsByYear).sort((a, b) => parseInt(b) - parseInt(a))
export const prerender = false
---

<Layout class="max-w-3xl">
  <PageHead slot="head" title="Blog" />
  <Breadcrumbs
    items={[
      { label: 'Blog', href: '/blog', icon: 'lucide:library-big' },
      { label: `Page ${page.currentPage}`, icon: 'lucide:book-copy' },
    ]}
  />

  <div class="flex min-h-[calc(100vh-18rem)] flex-col gap-y-8">
    {
      years.map((year) => (
        <section class="flex flex-col gap-y-4">
          <div class="font-medium">{year}</div>
          <ul class="flex flex-col gap-4">
            {postsByYear[year].map((post) => (
              <li>
                <BlogCard entry={post} />
              </li>
            ))}
          </ul>
        </section>
      ))
    }
  </div>

  <PaginationComponent
    currentPage={page.currentPage}
    totalPages={page.lastPage}
    baseUrl="/blog/"
    client:load
  />
</Layout>
