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'

async function fetchBlog(id: string) {
  const res = await fetch(`http://localhost:3000/api/blog/${id}`)
  if (!res.ok) return undefined
  return res.json();
}

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

  const id = (await params).id;
  const data = await fetchBlog(id) as Blog;
  const url = typeof data.photo === 'object' && data.photo?.sizes?.banner?.url;

  if(!data) {
    notFound();
  }

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

  return (
    <>
      <Section paddingBottom={"small"}>
        <Container>
          <Title title={data.title} color={"contrast"}></Title>
          <TextDiv text={data.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={true} />
            }
          </div>
        </Container>
      </Section>

      <Blocks content={data.content} />

    </>
  )
}