import React, { Fragment } from 'react'

import type { Page } from '@/payload-types'

import { ArchiveBlock } from '@/blocks/ArchiveBlock/Component'
import { CallToActionBlock } from '@/blocks/CallToAction/Component'
import { ContentBlock } from '@/blocks/Content/Component'
import { FormBlock } from '@/blocks/Form/Component'
import { MediaBlock } from '@/blocks/MediaBlock/Component'
import { SkillsBlock } from '@/blocks/Skills/Component'
import { SkillsMarqueeBlock } from '@/blocks/SkillsMarquee/Component'
import { KanbanColorBlock } from '@/blocks/KanbanColor/Component'
import { KanbanHoriBlock } from '@/blocks/KanbanHori/Component'
import { ShowcaseBlock } from '@/blocks/Showcase/Component'
import { AboutProfileBlock } from '@/blocks/AboutProfile/Component'
import { StatsStripBlock } from '@/blocks/StatsStrip/Component'
import { BentoRowBlock } from '@/blocks/BentoRow/Component'
import { ContactBlock } from '@/blocks/Contact/Component'
import { ToolStackBlock } from '@/blocks/ToolStack/Component'

const blockComponents = {
  archive: ArchiveBlock,
  content: ContentBlock,
  cta: CallToActionBlock,
  formBlock: FormBlock,
  mediaBlock: MediaBlock,
  skills: SkillsBlock,
  skillsMarquee: SkillsMarqueeBlock,
  kanbanColor: KanbanColorBlock,
  kanbanHori: KanbanHoriBlock,
  showcase: ShowcaseBlock,
  aboutProfile: AboutProfileBlock,
  statsStrip: StatsStripBlock,
  bentoRow: BentoRowBlock,
  contact: ContactBlock,
  toolStack: ToolStackBlock,
}

export const RenderBlocks: React.FC<{
  blocks: Page['layout'][0][]
}> = (props) => {
  const { blocks } = props

  const hasBlocks = blocks && Array.isArray(blocks) && blocks.length > 0

  if (hasBlocks) {
    return (
      <Fragment>
        {blocks.map((block, index) => {
          const { blockType } = block

          if (blockType && blockType in blockComponents) {
            const Block = blockComponents[blockType]

            if (Block) {
              return (
                <div key={index}>
                  <Block {...block} disableInnerContainer />
                </div>
              )
            }
          }
          return null
        })}
      </Fragment>
    )
  }

  return null
}
