import parse, { HTMLReactParserOptions } from 'html-react-parser';
import { SmartSlider } from './SmartSlider';
import PostGrid from '../WP/PostGrid/PostGrid.server';
import { CarouselSlide, PagePayload } from '@/types/entities';
import { transformLinks } from '@/lib/utils';
import EmblaCarousel from '../UI/EmblaCarousel/EmblaCarousel';
import { HTMLRenderer } from './HTMLRenderer';

const options: HTMLReactParserOptions = {
    replace: (domNode) => {
        if (domNode.type === 'text') {
            // Parse custom [tags] in text nodes
            const text = domNode.data;
            const parts = text.split(/(\[.*?\])/);
            if (parts.length > 1) {
                return parts.map((part, i) => {
                    if (part.startsWith('[') && part.endsWith(']')) {
                        // Handle your custom bracket tag
                        return <div>{JSON.stringify(part)}</div>;
                    }
                    return part;
                });
            }
        }
    }
};

const replaceShortcodes = (html: string) => {
    return html
        .replace(
            /\[the-post-grid\s+id="(\d+)"(?:\s+title="[^"]*")?\s*\]/g,
            (_m, gridId) =>
                `<div data-shortcode="post-grid" data-grid-id="${gridId}"></div>`
        )
        .replace(
            /\[smartslider3\s+slider="(\d+)"\s*\]/g,
            (_match, sliderId) =>
                `<div data-shortcode="smartslider3" data-slider-id="${sliderId}"></div>`
        );
};

// const transformLinks = (html: string) => {
//     // Regex to match https://specificdomain.com/?page_id= followed by numbers
//     // Using a more specific pattern to avoid matching other domains
//     const regex = /(https?:\/\/)?(www\.)?new.jkhsakha\.ru\/(?!wp-content)(\/[^\s"']*)/g

//     // Replace only the specific domain links with relative paths
//     return html.replace(regex, '$3');
// };

export const renderElementorContent = (content: string, payload?: PagePayload) => {
    const transformedContent = replaceShortcodes(
        transformLinks(content)
    )
    return (
        <div dangerouslySetInnerHTML={{__html: transformedContent}}></div>
        // <HTMLRenderer content={transformedContent} />
    )
}

export const renderPostContent = (content: string, payload?: PagePayload) => {

    const transformedContent = replaceShortcodes(
        transformLinks(content)
    )

    const slides: CarouselSlide[] = [
        {
            id: 0,
            title: "Тепло сердец - людям!",
            src: "/first_slide2.jpg",
        },
        {
            id: 1,
            title: "Личный кабинет",
            src: "/Личный-кабинет.jpg",
            href: "https://lk.jkhsakha.ru",
        },
        {
            id: 2,
            title: "Способы оплаты",
            src: "/Способ-оплаты.jpg",
            href: "/sposoby-oplaty/",
        }
    ]

    return (
        <div>
            {parse(transformedContent, {
                replace(domNode) {
                    if (
                        domNode &&
                        domNode.type === 'tag' && domNode.attribs?.['data-shortcode'] === 'smartslider3'
                    ) {
                        return (
                            <EmblaCarousel slides={slides} />
                        )
                        return (
                            <SmartSlider
                                slides={slides}
                                sliderId={(domNode as any).attribs['data-slider-id']}
                            />
                        );
                    } else if (
                        domNode &&
                        domNode.type === 'tag' && domNode.attribs?.['data-shortcode'] === 'post-grid'
                    ) {
                        const gridId = Number(domNode.attribs["data-grid-id"]);
                        if (!gridId) return null;
                        return (
                            <PostGrid id={gridId} page={payload?.page} />
                        );
                    } else if (
                        domNode &&
                        domNode.type === 'tag' && domNode.tagName === 'table'
                    ) {
                        domNode.attribs.class = (domNode.attribs.class || '') + ' table table-bordered w-full';
                        return (
                            domNode
                        );
                    } else if (
                        domNode &&
                        domNode.type === 'tag' && domNode.tagName === 'html'
                    ) {
                        return (
                            <></>
                        )
                    }
                },
            })}
        </div>
    )


    // Basic HTML sanitization - you might want to use a library like DOMPurify in production
    const createMarkup = () => {
        return { __html: transformedContent };
    };

    return <div dangerouslySetInnerHTML={createMarkup()} />;
}