import type { Page, PageBlocks } from "../tina/__generated__/types";
import { Content } from "./blocks/content";
import { Features } from "./blocks/features";
import { Hero } from "./blocks/hero";
import { Testimonial } from "./blocks/testimonial";
import { tinaField } from "tinacms/dist/react";
import { Carousel } from "./blocks/carousel";
import { ReactElement } from "react";

export const Blocks = (props: Omit<Page, "id" | "_sys" | "_values">) => {
    return (
        <>
            { props.blocks
                ? props.blocks.map((block, i) => {
                    return (
                        <div key={ i } data-tina-field={ tinaField(block) }>
                            <Block { ...block } />
                        </div>
                    );
                })
                : null }
        </>
    );
};

interface PageBlockProps<T = PageBlocks> {
    data: T
}

export type PageBlockFunction<T = PageBlocks> = ({
    data
}: PageBlockProps<T>) => ReactElement;

const Block = (block: PageBlocks): ReactElement<PageBlockProps, PageBlockFunction> => {
    switch (block.__typename) {
        case "PageBlocksContent":
            return <Content data={ block } />;
        case "PageBlocksHero":
            return <Hero data={ block } />;
        case "PageBlocksFeatures":
            return <Features data={ block } />;
        case "PageBlocksTestimonial":
            return <Testimonial data={ block } />;
        case "PageBlocksCarousel":
            return <Carousel data={ block } />;
        default:
            return null;
    }
};
