import { PageHeader } from '@/compositions/PageHeader/PageHeader'
import { fetchBlogPosts } from '@/fetch/blog'
import { BlogExcerpt } from '@/components/BlogExcerpt/BlogExcerpt'
import { Section } from '@/components/Section/Section'
import { Container } from '@/components/Container/Container'
import { NextPrevButtons } from '@/components/NextPrevButtons/NextPrevButtons'
import { getPhoto } from '@/utils/dto/gallery'

export const dynamic = 'force-dynamic'

const buildHref = (page: number): string =>
  page > 1 ? `/blog?page=${page}` : '/blog'

export default async function Page({
  searchParams,
}: {
  searchParams: Promise<{ page?: string }>
}) {
  const query = await searchParams

  const parsedPage = parseInt(query.page ?? '1', 10)
  const page = Number.isFinite(parsedPage) && parsedPage > 0 ? parsedPage : 1

  const blogs = await fetchBlogPosts(false, page)

  return (
    <>
      <PageHeader
        title={'Aktuelle Nachrichten'}
        description={'Im Blog der Pfarrei finden Sie aktuelle Nachrichten und erfahren alles über das Gemeindeleben, kommende Veranstaltungen und besondere Gottesdienste.'}
      />

      <Section padding={'small'}>
        <Container>
          {
            blogs?.docs.map(blog =>
              <BlogExcerpt
                key={blog.id}
                id={blog.id}
                title={blog.title}
                excerpt={blog.content.excerpt}
                photo={getPhoto('thumbnail', blog.photo)}
              />)
          }
        </Container>
      </Section>

      {(blogs?.hasPrevPage || blogs?.hasNextPage) && (
        <Section padding={'small'}>
          <NextPrevButtons
            prev={
              blogs.hasPrevPage && blogs.prevPage
                ? { href: buildHref(blogs.prevPage), text: 'Vorige Seite' }
                : undefined
            }
            next={
              blogs.hasNextPage && blogs.nextPage
                ? { href: buildHref(blogs.nextPage), text: 'Nächste Seite' }
                : undefined
            }
          />
        </Section>
      )}
    </>
  )
}
