import { PageHeader } from '@/compositions/PageHeader/PageHeader'
import { Container } from '@/components/Container/Container'
import { Section } from '@/components/Section/Section'
import { NextPrevButtons } from '@/components/NextPrevButtons/NextPrevButtons'
import { fetchMagazines } from '@/fetch/magazine'
import { siteConfig } from '@/config/site'
import { Media } from '@/payload-types'
import Image from 'next/image'
import styles from './styles.module.scss'

export const dynamic = 'force-dynamic'

type Props = {
  searchParams: Promise<{ page?: string }>
}

export default async function MagazinArchivPage({ searchParams }: Props) {
  const { page: pageParam } = await searchParams
  const page = Math.max(1, parseInt(pageParam ?? '1', 10) || 1)

  const result = await fetchMagazines(page)

  return (
    <>
      <PageHeader
        title={`${siteConfig.magazineName} – Archiv`}
        description={'Alle bisherigen Ausgaben unseres Pfarrei-Magazins auf einen Blick.'}
      />

      <Section padding={'small'}>
        <Container>
          <div className={styles.grid}>
            {result.docs.map((magazine) => {
              const cover = typeof magazine.cover === 'object' ? (magazine.cover as Media) : null
              const pdfUrl =
                typeof magazine.document === 'object' ? magazine.document.url ?? null : null

              if (!cover?.url || !pdfUrl) return null

              return (
                <a
                  key={magazine.id}
                  href={pdfUrl}
                  target="_blank"
                  rel="noopener noreferrer"
                  className={styles.item}
                >
                  <Image
                    src={cover.url}
                    width={cover.width ?? 300}
                    height={cover.height ?? 400}
                    alt={`${siteConfig.magazineName}`}
                    unoptimized
                    className={styles.cover}
                  />
                </a>
              )
            })}
          </div>

          {result.docs.length === 0 && <p>Keine Ausgaben gefunden.</p>}
        </Container>
      </Section>

      {(result.hasPrevPage || result.hasNextPage) && (
        <Section padding={'small'}>
          <NextPrevButtons
            prev={
              result.hasPrevPage && result.prevPage
                ? { href: `/pfarrei/magazin/archiv?page=${result.prevPage}`, text: 'Neuere Ausgaben' }
                : undefined
            }
            next={
              result.hasNextPage && result.nextPage
                ? { href: `/pfarrei/magazin/archiv?page=${result.nextPage}`, text: 'Ältere Ausgaben' }
                : undefined
            }
          />
        </Section>
      )}
    </>
  )
}
