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 { isAuthenticated } from '@/utils/auth'
import { RefreshRouteOnSave } from '@/components/RefreshRouteOnSave/RefreshRouteOnSave'
import { draftMode } from 'next/headers'

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

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

  if (!page) return {}

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

export default async function DynamicPage({ params }: Props) {
  const slug = (await params).slug
  const { isEnabled: isDraft } = await draftMode()
  const page = await fetchPageBySlug(slug || "", isDraft)
  const authenticated = await isAuthenticated()

  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}
      />
    </>
  )
}
