import { notFound } from 'next/navigation'
import { fetchPageBySlug } from '@/fetch/pages'
import { Blocks } from '@/compositions/Blocks/Blocks'
import { Metadata } from 'next'
import { AdminMenu } from '@/components/AdminMenu/AdminMenu'
import { Section } from '@/components/Section/Section'
import { getRequestAuth } from '@/utils/auth'
import { RefreshRouteOnSave } from '@/components/RefreshRouteOnSave/RefreshRouteOnSave'

type Props = {
  params: Promise<{ slug?: string[] }>
}

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const slug = (await params).slug
  const page = await fetchPageBySlug(slug?.join('/') || "")

  if (!page) return {}

  return {
    title: page.title,
    description: page.description || undefined,
  }
}

export default async function DynamicPage({ params }: Props) {
  const slug = (await params).slug
  const { authenticated, isDraft } = await getRequestAuth()
  const page = await fetchPageBySlug(slug?.join('/') || "", isDraft)

  if (!page) {
    notFound()
  }

  if (!authenticated && page._status !== 'published') {
    notFound()
  }

  const firstBlockType = page.content?.[0]?.blockType
  const needsTopPadding =
    firstBlockType === 'title' || firstBlockType === 'text'

  return (
    <>
      {isDraft && <RefreshRouteOnSave />}
      {needsTopPadding && <Section padding={'medium'} />}

      {page.content && page.content.length > 0 && (
        <Blocks content={page.content} />
      )}

      <AdminMenu
        collection={'pages'}
        id={page.id}
        isAuthenticated={authenticated}
      />
    </>
  )
}
