import { MDXComponents } from "mdx/types";
import CodeBlock from "../elements/CodeBlock";
import H1 from "../layout/H1";
import H4 from "../layout/H4";
import React from "react";
import twuiSlugify from "../utils/slugify";
import H2 from "../layout/H2";
import P from "../layout/P";
import H3 from "../layout/H3";

type Params = {
    components: MDXComponents;
    codeBgColor?: string;
};

export function useMDXComponents(params?: Params) {
    const codeBgColor = params?.codeBgColor || "#000000";

    return {
        components: {
            h1: ({ children }) => <H1>{children}</H1>,
            h4: ({ children }) => <H4>{children}</H4>,
            pre: ({ children, ...props }) => {
                if (React.isValidElement(children) && children.props) {
                    return (
                        // @ts-ignore
                        <CodeBlock {...props} backgroundColor={codeBgColor}>
                            {/* @ts-ignore */}
                            {children.props.children}
                        </CodeBlock>
                    );
                }
                return (
                    // @ts-ignore
                    <CodeBlock {...props} backgroundColor={codeBgColor}>
                        {children}
                    </CodeBlock>
                );
            },
            h2: ({ children }) => {
                const slug = twuiSlugify(children?.toString());

                return (
                    <a
                        href={`#${slug}`}
                        id={slug}
                        className="twui-docs-header-anchor"
                    >
                        <H2 className="pt-4 m-0 mb-4 text-2xl">{children}</H2>
                    </a>
                );
            },
            h3: ({ children }) => {
                const slug = twuiSlugify(children?.toString());

                return (
                    <a
                        href={`#${slug}`}
                        id={slug}
                        className="twui-docs-header-anchor"
                    >
                        <H3 className="pt-4 m-0 mb-4 text-xl">{children}</H3>
                    </a>
                );
            },
            img: (props) => (
                // @ts-ignore
                <img
                    {...props}
                    className="w-full h-auto shadow-lg rounded-default overflow-hidden"
                />
            ),
            p: ({ children }) => (
                <P className="mt-2 mb-6 max-w-none py-0">{children}</P>
            ),
            li: ({ children }) => <li className="w-full">{children}</li>,
            ...params?.components,
        } as MDXComponents,
        codeBgColor: "rgb(7 12 22)",
    };
}
