import { Blog } from "@/payload-types"
import { Container } from '@/components/Container/Container'
import { HTMLText } from '@/components/Text/HTMLText'
import { Section } from '@/components/Section/Section'
import { Button } from '@/components/Button/Button'
import { ContactSection } from '@/compositions/ContactSection/ContactSection'
import { Gallery } from '@/components/Gallery/Gallery'
import { transformGallery } from '@/utils/dto/gallery'

type BlocksProps = {
  content: Blog['content']
}

export function Blocks({ content }: BlocksProps) {

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

  return (
    <>
      <div>
        {content.map(item => {
          if (item.blockType === "text" && item.content_html) {
            return (
              <Container key={item.id}>
                <HTMLText width={item.width} html={item.content_html} />
              </Container>
            );
          }

          if (item.blockType === "document" && typeof item.file === "object") {
            return (
              <Container key={item.id}>
                <Section padding={"medium"}>
                  <Button size={"lg"} href={item.file.url || "notfound"} schema={"contrast"}>{item.button}</Button>
                </Section>
              </Container>
            )
          }

          if (item.blockType === "contactform") {
            return (
              <ContactSection
                key={item.id}
                title={item.title}
                description={item.description}
                backgroundColor={"off-white"}
              />
            )
          }

          if (item.blockType === "gallery") {
            return (
              <Section key={item.id}>
                <Gallery items={transformGallery(item.items)} />
              </Section>
            )
          }
        })}
      </div>

      { shouldAddMargin &&
        <Section></Section>
      }
    </>
  )
}