import { Section } from '@/components/Section/Section'
import { Container } from '@/components/Container/Container'
import { Title } from '@/components/Title/Title'
import { TextDiv } from '@/components/Text/TextDiv'
import { Blog } from '@/payload-types'
import { notFound } from 'next/navigation'
import { readableDateTime } from '@/utils/readableDate'
import { HR } from '@/components/HorizontalRule/HorizontalRule'
import Image from 'next/image'
import styles from './styles.module.scss'
import { Blocks } from '@/compositions/Blocks/Blocks'
import { canView, getRequestAuth } from '@/utils/auth'
import { AdminMenu } from '@/components/AdminMenu/AdminMenu'
import { RefreshRouteOnSave } from '@/components/RefreshRouteOnSave/RefreshRouteOnSave'
import { fetchBlog } from '@/fetch/blog'

export default async function BlogPage({ params }: { params: Promise<{id: string}>}){

  const id = (await params).id;
  const { authenticated, isDraft } = await getRequestAuth()
  const data = await fetchBlog(id, isDraft) as Blog;
  const url = typeof data.photo === 'object' && data.photo?.sizes?.banner?.url;

  if (!canView(data, authenticated)) notFound()

  // determine if some margin at the bottom should be added
  const length = data.content.content.length;
  const shouldAddMargin = data.content.content[length - 1].blockType === "text"

  return (
    <>
      {isDraft && <RefreshRouteOnSave />}
      <Section paddingBottom={"small"}>
        <Container>
          <Title title={data.title} color={"contrast"}></Title>
          <TextDiv text={data.content.excerpt} />
          <p className={styles.published}>
            Publiziert am {readableDateTime(data.createdAt)}
          </p>
        </Container>
        <HR/>
        <Container>
          <div>
            { typeof url === "string" &&
              <Image className={styles.image} src={url} width={1100} height={400} alt={""} unoptimized={false} />
            }
          </div>
        </Container>
      </Section>

      <Blocks content={data.content.content} />

      <AdminMenu
        collection={"blog"}
        id={id}
        isAuthenticated={authenticated}
      />

    </>
  )
}