import LazyImage from "@insite/mobius/LazyImage";
import Link from "@insite/mobius/Link";
import ListItem, { OrderedList, UnorderedList } from "@insite/mobius/Lists";
import Typography, { TypographyProps } from "@insite/mobius/Typography";
import getFocalPointStylesFromMobius from "@insite/mobius/utilities/getFocalPointStyles";
import { DOMNode, domToReact, HTMLReactParserOptions } from "html-react-parser";
import * as React from "react";

export const parserOptions: HTMLReactParserOptions = {
    replace: node => {
        if (!("name" in node && "children" in node)) {
            return;
        }

        const { name, children, attribs = { style: "" } } = node;
        const { style, class: className, ...otherAttribs } = attribs;

        otherAttribs.className = className;

        if (name && ["h1", "h2", "h3", "h4", "h5", "h6", "body", "p", "legend"].includes(name) && children) {
            return (
                <Typography css={style as any} {...otherAttribs} variant={name as TypographyProps["variant"]}>
                    {children && domToReact(children as DOMNode[], parserOptions)}
                </Typography>
            );
        }
        if (name === "ul") {
            return (
                <UnorderedList css={style as any} {...otherAttribs}>
                    {children && domToReact(children as DOMNode[], parserOptions)}
                </UnorderedList>
            );
        }
        if (name === "ol") {
            return (
                <OrderedList css={style as any} {...otherAttribs}>
                    {children && domToReact(children as DOMNode[], parserOptions)}
                </OrderedList>
            );
        }
        if (name === "li") {
            return (
                <ListItem css={style as any} {...otherAttribs}>
                    {children && domToReact(children as DOMNode[], parserOptions)}
                </ListItem>
            );
        }
        if (name === "img") {
            const { alt, ...remainingAttribs } = otherAttribs;
            return <LazyImage as="span" altText={alt} css={style as any} {...remainingAttribs} />;
        }
        if (name === "a") {
            return (
                <Link css={style as any} id={otherAttribs.name} {...otherAttribs}>
                    {children && domToReact(children as DOMNode[], parserOptions)}
                </Link>
            );
        }
    },
};

export function getFocalPointStyles(
    focalPoint:
        | "topLeft"
        | "topCenter"
        | "topRight"
        | "centerLeft"
        | "center"
        | "centerRight"
        | "bottomLeft"
        | "bottomCenter"
        | "bottomRight",
) {
    return getFocalPointStylesFromMobius(focalPoint);
}
