import parse, { HTMLReactParserOptions } from 'html-react-parser';
import { SmartSlider } from './SmartSlider';
import PostGrid from '../WP/PostGrid/PostGrid.server';
import { PagePayload } from '@/types/entities';

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 renderPostContent = (content: string, payload?: PagePayload) => {

    const transformedContent = replaceShortcodes(
        transformLinks(content)
    )

    return (
        <div>
            {parse(transformedContent, {
                replace(domNode) {
                    if (
                        domNode &&
                        domNode.type === 'tag' && domNode.attribs?.['data-shortcode'] === 'smartslider3'
                    ) {
                        return (
                            <SmartSlider
                                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
                        );
                    }
                },
            })}
        </div>
    )


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

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