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";
import { Title } from "./blocks/title";
import { FacebookPageTimeline } from "./blocks/facebook-page-timeline";

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 } />;
        case "PageBlocksTitle":
            return <Title data={ block } />;
        case "PageBlocksFacebookPageTimeline":
            return <FacebookPageTimeline data={ block } />;
        default:
            return null;
    }
};
