import Header from "./LiveEdit/Header";
import Menu from "./LiveEdit/Menu";
import Colors from "./Settings/Colors";
import Typography from "./Settings/Typography";
import Excludes from "./Settings/Excludes";
import CustomCss from "./Settings/CustomCss";
import Switch from "./Settings/Switch";
import {SettingsProvider} from "../contexts/SettingsContext";
import Images from "./Settings/Images";
import Videos from "./Settings/Videos";
import Animation from "./Settings/Animation";
import ProModal from "./ProModal";
import HandleChange from "./LiveEdit/HandleChange";

const {FormToggle} = wp.components;
const {useState, useEffect} = React;

export default function LiveEdit({isEditor}) {

    const {isPro, settings, editDetails} = dracula;

    let settingsData = settings;

    if (isPro) {

        if (isEditor && editDetails?.settings) {
            settingsData = editDetails.settings;
        }

        settingsData.excludes = settingsData.excludes ? settingsData.excludes.filter((item, index) => !!item || index === 0) : [''];
    }

    const [data, setData] = useState(settingsData);

    let {pageSpecificDarkMode = false} = data;

    // Get menu from url params
    const urlParams = new URLSearchParams(window.location.search);
    const [menu, setMenu] = useState(urlParams.get('tab') || '');

    // Handle Dragging
    const [position, setPosition] = useState({right: 15, top: 47});

    const handleMouseDown = (event) => {
        if (!isPro || isEditor && 'elementor' !== isEditor) return;
        event.preventDefault();

        const initialX = window.innerWidth - event.clientX - position.right;
        const initialY = event.clientY - position.top;

        const handleMouseMove = (event) => {
            setPosition({
                right: Math.min(Math.max(window.innerWidth - event.clientX - initialX, 0), window.innerWidth),
                top: Math.min(Math.max(event.clientY - initialY, 0), window.innerHeight),
            });
        };

        document.addEventListener('mousemove', handleMouseMove);

        const handleMouseUp = () => {
            document.removeEventListener('mousemove', handleMouseMove);
        };

        document.addEventListener('mouseup', handleMouseUp);
    };

    const style = {}

    if (!isEditor) {
        style.top = position.top;
        style.right = position.right;
    }

    useEffect(() => {
        const param = 'dracula-live-edit';
        const url = new URL(window.location.href);

        if (dracula.isAdmin) return;

        // Add parameter if missing
        if (!url.searchParams.has(param)) {
            url.searchParams.set(param, '1');
            window.history.replaceState(null, '', url.toString());
        }

        return () => {
            const cleanupUrl = new URL(window.location.href);

            // Remove parameter on unmount
            if (cleanupUrl.searchParams.has(param)) {
                cleanupUrl.searchParams.delete(param);
                window.history.replaceState(null, '', cleanupUrl.toString());
            }
        }

    }, []);

    return (
        <div
            className={`dracula-ignore dracula-live-edit ${isEditor ? `dracula-editor-live-edit dracula-editor-${isEditor}` : ''}`}
            style={style}>

            {(!isEditor || 'elementor' === isEditor) &&
                <HandleChange data={data} isEditor={isEditor} isLiveEdit/>
            }

            {isEditor &&
                <>
                    <HandleChange data={data} isEditor={isEditor} isLiveEdit/>

                    <div className="dracula-settings-content">
                        <div className="settings-field field-page-specific-dark-mode">
                            <h4 className={`settings-field-label`}>{wp.i18n.__('Page-Specific Dark Mode', 'dracula-dark-mode')} </h4>
                            <div className="settings-field-content">
                                <FormToggle
                                    checked={pageSpecificDarkMode}
                                    onChange={() => setData({...data, pageSpecificDarkMode: !pageSpecificDarkMode})}
                                />

                                <p className="description">{wp.i18n.__('Enable and customize page-specific dark mode for this page', 'dracula-dark-mode')}</p>
                            </div>
                        </div>
                    </div>
                </>
            }

            {(!isPro || !isEditor || !!pageSpecificDarkMode) &&
                <SettingsProvider value={{menu, data, setData, isLiveEdit: true, isEditor}}>

                    {!isEditor && <Header handleMouseDown={handleMouseDown} setMenu={setMenu}/>}

                    <Menu menu={menu} setMenu={setMenu}/>

                    {'colors' === menu && <Colors/>}
                    {'adjustments' === menu && <Colors/>}
                    {'toggle' === menu && <Switch/>}
                    {'animation' === menu && <Animation/>}
                    {'typography' === menu && <Typography/>}
                    {'excludes' === menu && <Excludes/>}
                    {'images' === menu && <Images/>}
                    {'videos' === menu && <Videos/>}
                    {'css' === menu && <CustomCss/>}
                </SettingsProvider>
            }

            {!isPro &&
                <ProModal
                    isDismissable={false}
                    text={wp.i18n.__('Upgrade to PRO to set page specific dark mode appearance.', 'dracula-dark-mode')}
                    watchVideo={{
                        id: 'OZfn_4tiq9o',
                        title: wp.i18n.__('Page Specific Dark Mode Appearance', 'dracula-dark-mode')
                    }}
                />
            }

        </div>
    )
}
