import React, { Fragment } from "react";

import type { Page } from "@/payload-types";
import { ContentBlock } from "./Content";
import { FormBlock } from "./Form";

const blockComponents = {
  contentBlock: ContentBlock,
  formBlock: FormBlock,
};

export const RenderBlocks: React.FC<{
  blocks: Page["layout"];
}> = (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 null;

            if (blockType === "formBlock") {
              return (
                <div className="my-10" key={index}>
                  <FormBlock
                    id={block.id}
                    enableIntro={block.enableIntro}
                    introContent={block.introContent}
                    form={block.form}
                  />
                </div>
              );
            } else {
              return (
                <div className="my-10" key={index}>
                  {/* @ts-ignore */}
                  <Block {...block} disableInnerContainer />
                </div>
              );
            }
          }
          return null;
        })}
      </Fragment>
    );
  }

  return null;
};
