import React from "react";
import { Container } from "../util/container";
import { Section } from "../util/section";
import { TinaMarkdown } from "tinacms/dist/rich-text";
import type { Template } from "tinacms";
import { PageBlocksContent } from "../../tina/__generated__/types";
import { tinaField } from "tinacms/dist/react";
import { PageBlockFunction } from "../blocks-renderer";
import inlineComponents, { richTextTemplates } from "../inline/inline-definitions";
import sanitizeHtml from "sanitize-html";

const HTMLInline = (props: { value: string }) => {
    const createSanitizedMarkup = (text: string) => {
        return { __html: sanitizeHtml(text, {
            allowedAttributes: {
                div: [ "class" ]
            }
        }) };
    };

    return <span dangerouslySetInnerHTML={ createSanitizedMarkup(props.value) } />;
};

export const Content: PageBlockFunction<PageBlocksContent> = ({ data }) => {
    return (
        <Section>
            <Container
                className={ "" }
                data-tina-field={ tinaField(data, "body") }
                size="large"
                width="medium"
            >
                <TinaMarkdown components={ { ...inlineComponents, html: props => <HTMLInline { ...props } /> } } content={ data.body } />
            </Container>
        </Section>
    );
};

export const contentBlockSchema: Template = {
    name: "content",
    label: "Content",
    ui: {
        previewSrc: "/blocks/content.png",
        defaultItem: {
            body: "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec odio. Quisque volutpat mattis eros. Nullam malesuada erat ut turpis. Suspendisse urna nibh, viverra non, semper suscipit, posuere a, pede."
        }
    },
    fields: [
        {

            type: "rich-text",
            label: "Body",
            name: "body",
            templates: richTextTemplates,
            isBody: true
        }
    ]
};
