import {Tooltip} from "react-tooltip";
import {getConfig, handleAnimation, promptFeedback, useMounted} from '../includes/functions';

const {useState, useEffect, useRef} = React;

import Layout1 from "./Layouts/Layout1";
import Layout2 from "./Layouts/Layout2";
import Layout3 from "./Layouts/Layout3";
import Layout4 from "./Layouts/Layout4";
import Layout5 from "./Layouts/Layout5";

export default function Toggle({style, data, isPreview, previewMode, isFloating}) {

    const {isPro, settings = {}} = dracula;

    const {
        showTooltip,
        lightTooltipText = wp.i18n.__('Toggle Dark Mode', 'dracula-dark-mode'),
        darkTooltipText = wp.i18n.__('Toggle Light Mode', 'dracula-dark-mode'),
        enableAnalytics,
        enableFeedback,
        attentionEffect,
        draggableToggle,
        matchOsTheme = true,
    } = settings;

    const [mode, setMode] = useState(window.draculaMode ? window.draculaMode : (window.draculaDarkMode.isEnabled() ? 'dark' : 'light'));

    const toggleRef = useRef(null);

    const isMounted = useMounted();

    useEffect(() => {
        if (!previewMode) return;

        setMode(previewMode);

    }, [previewMode]);

    // Add system theme detection
    useEffect(() => {
        if (!matchOsTheme) return;

        // check saved mode
        const savedMode = localStorage?.getItem('dracula_mode');

        if (!!savedMode) return;

        const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');

        const handleChange = (e) => {
            const currentMode = e.matches ? 'dark' : 'light';
            setMode(currentMode);
        };

        // Set initial value
        handleChange(mediaQuery);

        // Listen for changes
        mediaQuery.addEventListener('change', handleChange);

        return () => mediaQuery.removeEventListener('change', handleChange);
    }, [matchOsTheme]);

    // Handle mode change
    useEffect(() => {
        if (!isMounted) return;

        if (isPreview) {
            jQuery('.form-preview').removeClass('state-light state-dark').addClass(`state-${mode}`);
            return;
        }

        const {pageTransition} = dracula.settings;
        handleAnimation(mode, '', pageTransition);

        if ('dark' === mode) {
            draculaDarkMode.enable(getConfig());
        } else if ('auto' === mode) {
            draculaDarkMode.auto(getConfig());
        } else {
            if (draculaDarkMode.isEnabled()) {
                draculaDarkMode.disable();
            }
        }

        localStorage.setItem('dracula_mode', mode);

    }, [mode]);

    // Handle Attention Effect
    useEffect(() => {
        if (!isPro || !isFloating) return;

        clearInterval(window.draculaEffectInterval);

        const element = jQuery('.dracula-toggle-wrap.floating .dracula-toggle');
        if (!element.length) return;

        function removeEffectClass() {
            clearInterval(window.draculaEffectInterval);
            const matchedClasses = (element.attr('class').match(/\bdracula-effect-\S+/g) || []);
            element.removeClass(matchedClasses.join(' '));
        }

        if (!attentionEffect || 'none' === attentionEffect) {
            removeEffectClass();
            return;
        }


        window.draculaEffectInterval = setInterval(() => {
            // 1. Remove the class
            removeEffectClass();

            // 2. Small delay before re-adding (optional but may help)
            setTimeout(() => {
                element.addClass(`dracula-effect-${attentionEffect}`);
            }, 50);

        }, 7000);

        return () => clearInterval(window.draculaEffectInterval);

    }, [attentionEffect]);

    return (
        <>
            {!!style &&
                <>
                    {isFloating && draggableToggle && <>
                        <svg
                            data-tooltip-content={wp.i18n.__('Move', 'dracula-dark-mode')}
                            data-tooltip-id="dracula-toggle-move"
                            xmlns="http://www.w3.org/2000/svg"
                            viewBox="0 0 20 20"
                            className="dracula-toggle-move">
                            <rect x="0" fill="none" width="20" height="20"/>
                            <g>
                                <path d="M19 10l-4 4v-3h-4v4h3l-4 4-4-4h3v-4H5v3l-4-4 4-4v3h4V5H6l4-4 4 4h-3v4h4V6z"/>
                            </g>
                        </svg>
                        <Tooltip
                            id="dracula-toggle-move"
                            effect="solid"
                            variant={'dark' === mode ? 'light' : 'dark'}
                        />
                    </>}

                    {[14, 17, 18].includes(parseInt(style)) &&
                        <div
                            className={`dracula-toggle dracula-ignore style-${style} mode-${mode}`}
                            aria-label={wp.i18n.__('Dark Mode Toggle', 'dracula-dark-mode')}
                            dangerouslySetInnerHTML={{__html: dracula?.switches[style].replace(/\s+/g, ' ').trim()}}
                            onClick={(e) => {
                                if (isDragging) return;


                                if (isDragging || [14, 17, 18].includes(parseInt(style))) return;

                                setMode(mode => {
                                    if (mode === 'light' || (mode === 'auto' && !draculaDarkMode.isEnabled())) {
                                        return 'dark';
                                    } else {
                                        return 'light';
                                    }
                                });


                                if (isDragging || [14, 17, 18].includes(parseInt(style))) return;

                                setMode(mode => {
                                    if (mode === 'light' || (mode === 'auto' && !draculaDarkMode.isEnabled())) {
                                        return 'dark';
                                    } else {
                                        return 'light';
                                    }
                                });

                                // Analytics
                                if (isPro && enableAnalytics) {

                                    // Send activation/deactivation analytics event
                                    wp.ajax.post('dracula_track_analytics', {type: 'dark' === mode ? 'activation' : 'deactivation'});

                                    // Prompt feedback
                                    if (enableFeedback) {
                                        let prevCount = localStorage.getItem('dracula_toggle_count');
                                        if ('feedback' !== prevCount) {

                                            prevCount = parseInt(prevCount || 0);
                                            localStorage.setItem('dracula_toggle_count', (prevCount + 1).toString());

                                            if (prevCount > 4 && prevCount % 5 === 0) {
                                                setTimeout(() => {
                                                    promptFeedback();
                                                }, 1000);
                                            }
                                        }
                                    }
                                }

                                if ([14, 17, 18].includes(parseInt(style))) return;

                                setMode(mode => {
                                    if (mode === 'light' || (mode === 'auto' && !draculaDarkMode.isEnabled())) {
                                        return 'dark';
                                    } else {
                                        return 'light';
                                    }
                                });

                            }}>
                        </div>}

                    {![14, 17, 18].includes(parseInt(style)) &&
                        <button
                            type="button"
                            className={`dracula-toggle dracula-ignore style-${style} mode-${mode}`}
                            aria-label={wp.i18n.__('Dark Mode Toggle', 'dracula-dark-mode')}
                            dangerouslySetInnerHTML={{__html: dracula?.switches[style].replace(/\s+/g, ' ').trim()}}
                            onClick={(e) => {
                                if (isDragging) return;


                                if (isDragging || [14, 17, 18].includes(parseInt(style))) return;

                                setMode(mode => {
                                    if (mode === 'light' || (mode === 'auto' && !draculaDarkMode.isEnabled())) {
                                        return 'dark';
                                    } else {
                                        return 'light';
                                    }
                                });


                                if (isDragging || [14, 17, 18].includes(parseInt(style))) return;

                                setMode(mode => {
                                    if (mode === 'light' || (mode === 'auto' && !draculaDarkMode.isEnabled())) {
                                        return 'dark';
                                    } else {
                                        return 'light';
                                    }
                                });

                                // Analytics
                                if (isPro && enableAnalytics) {

                                    // Send activation/deactivation analytics event
                                    wp.ajax.post('dracula_track_analytics', {type: 'dark' === mode ? 'activation' : 'deactivation'});

                                    // Prompt feedback
                                    if (enableFeedback) {
                                        let prevCount = localStorage.getItem('dracula_toggle_count');
                                        if ('feedback' !== prevCount) {

                                            prevCount = parseInt(prevCount || 0);
                                            localStorage.setItem('dracula_toggle_count', (prevCount + 1).toString());

                                            if (prevCount > 4 && prevCount % 5 === 0) {
                                                setTimeout(() => {
                                                    promptFeedback();
                                                }, 1000);
                                            }
                                        }
                                    }
                                }

                                if ([14, 17, 18].includes(parseInt(style))) return;

                                setMode(mode => {
                                    if (mode === 'light' || (mode === 'auto' && !draculaDarkMode.isEnabled())) {
                                        return 'dark';
                                    } else {
                                        return 'light';
                                    }
                                });

                            }}>
                        </button>}
                </>
            }

            {/* Custom Toggle */}
            {
                !!data && !!data.layout &&
                <>
                    <button
                        type="button"
                        data-tooltip-content={data.showTooltip ? (mode === 'dark' ? data.darkTooltipText : data.tooltipText) : ''}
                        data-tooltip-id={`dracula-toggle-tooltip-${data.id}`}
                        ref={toggleRef}
                        className={`dracula-toggle dracula-ignore layout-${data.layout} mode-${mode}`}
                        onClick={() => {
                            if (isDragging) return;

                            setMode(mode => 'light' === mode ? 'dark' : 'light')
                        }}
                        style={{
                            '--toggle-icon-light': `url("${data.customLightIcon ? data.customLightIcon : `${dracula.pluginUrl}/assets/images/icons/${data.lightIcon}.svg`}") no-repeat center / contain`,
                            '--toggle-icon-dark': `url("${data.customDarkIcon ? data.customDarkIcon : `${dracula.pluginUrl}/assets/images/icons/${data.darkIcon}.svg`}") no-repeat center / contain`,
                            '--toggle-width': data.width + 'px',
                            '--toggle-padding': data.padding + 'px',
                            '--toggle-text-size': data.textSize + 'px',
                            '--toggle-bg-light': data.lightBackgroundColor,
                            '--toggle-bg-dark': data.darkBackgroundColor,
                            '--toggle-text-color-light': data.lightTextColor,
                            '--toggle-text-color-dark': data.darkTextColor,
                            '--toggle-border-w': data.borderWidth + 'px',
                            '--toggle-border-color-light': data.lightBorderColor,
                            '--toggle-border-color-dark': data.darkBorderColor,
                            '--toggle-border-radius': data.borderRadius + 'px',
                            '--toggle-icon-spacing': data.iconSpacing + 'px',
                        }}
                    >

                        {1 == data.layout && <Layout1 data={data}/>}
                        {2 == data.layout && <Layout2 data={data}/>}
                        {3 == data.layout && <Layout3 data={data}/>}
                        {4 == data.layout && <Layout4 data={data}/>}
                        {5 == data.layout && <Layout5 data={data}/>}

                    </button>

                    {(!!isFloating && !!data.showTooltip) &&
                        <Tooltip
                            id={`dracula-toggle-tooltip-${data.id}`}
                            effect="solid"
                            className={"dracula-tooltip dracula-toggle-tooltip dracula-ignore"}
                            variant={'dark' === mode ? 'light' : 'dark'}
                        />
                    }
                </>
            }

        </>
    )
}