import { useBlocks, useMeta } from '../../metaExtractor/metaContext'
import { Block } from './blocks'

export const MetaBlock = ({
  filterBy,
  block,
}: Based.UI.Extractor.FilterProps) => {
  const renderBlock = (
    block: Based.UI.Extractor.BlocksDescriptorResult,
    blocks?: Based.UI.Playground.Content.Block['blocks'],
    componentName?: string,
  ) => {
    if (!block) return null

    switch (block.type) {
      case 'typography':
        return (
          <Block
            key={block.id}
            componentName={componentName}
            blocks={blocks}
            name={block.name}
            id={block.id}
            type={block.type}
            style={block.style}
            description={block.description}
            render={block.render}
          />
        )

      case 'color':
        return (
          <Block
            key={block.id}
            componentName={componentName}
            blocks={blocks}
            name={block.name}
            id={block.id}
            type={block.type}
            style={block.style}
            description={block.description}
            render={block.render}
            code={block.code}
          />
        )

      case 'component':
        return (
          <Block
            key={block.id}
            componentName={componentName}
            blocks={blocks}
            name={block.name}
            id={block.id}
            type={block.type}
            description={block.description}
            render={block.render}
            code={block.code}
            style={block.style}
          />
        )
    }
  }

  const { blocks } = useBlocks(filterBy)

  if (block) {
    const { meta } = useMeta(filterBy)

    const findBlockById = (
      blocks: Based.UI.Extractor.BlocksDescriptorResult[],
      idToFind: string,
    ): Based.UI.Extractor.BlocksDescriptorResult => {
      return blocks.find((block) => block.id === idToFind)!
    }

    const getBlockDetails = (
      blocks: Based.UI.Extractor.BlocksDescriptor[],
    ): { id: string; name: string }[] => {
      return blocks.map((block) => ({
        id: block.id!,
        name: block.name,
      }))
    }

    return renderBlock(
      findBlockById(blocks, block),
      getBlockDetails(blocks),
      meta.name,
    )
  }

  const hasBlocks = blocks && blocks.length > 0

  return hasBlocks && blocks.map((block) => renderBlock(block), [block])
}
