import { Tooltip } from "react-tooltip";
import { addDarkModeSelectorPrefix, useMounted } from "../../includes/functions";
import SettingsContext from "../../contexts/SettingsContext";
import Header from "./Header";
import LiveEditButton from "./LiveEditButton";
import { showProModal } from "../ProModal";

const { useEffect, useContext } = React;

export default function CustomCss() {

    const { isPro } = dracula;

    const { data, setData, isLiveEdit } = useContext(SettingsContext);

    const { customCss, lightModeCSS } = data;

    useEffect(() => {
        const cssEditors = document.querySelectorAll('.dracula-custom-css-editor');

        cssEditors.forEach(editor => {
            const isLightMode = editor.classList.contains('editor-light-mode');

            const instance = wp.codeEditor.initialize(editor, {
                ...wp.codeEditor.defaultSettings, // Spread the default settings
                mode: 'css',
                wordWrap: true,
                tabSize: 2,
                autoComplete: {
                    enable: true,
                    showDescriptions: true,
                    caseSensitive: true,
                    autoTrigger: true,
                    delay: 0,
                    maxItems: 10,
                    sortBy: 'score',
                    maxLength: 0,
                    maxResults: 10,
                    highlightMatches: true,
                    maxHighlightLength: 0,
                    style: 'popup',
                },
                showGutter: true,
                showPrintMargin: true,
                highlightActiveLine: true,
                showLineNumbers: true,
                enableBasicAutocompletion: true,
                enableLiveAutocompletion: true,
                enableCodeFolding: true,
                enableCodeFormatting: true,
            });

            instance.codemirror.on('change', (codemirror) => {

                const value = codemirror.getValue();

                if (isLightMode) {
                    setData({ ...data, lightModeCSS: value });
                } else {
                    setData({ ...data, customCss: value });
                }
            });
        });

    }, []);

    const isMounted = useMounted();

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

        try {
            const compiledCss = addDarkModeSelectorPrefix(customCss);

            setData({ ...data, compiledCss });

            if (isLiveEdit) {
                let cssElement = jQuery('#dracula-custom-css');
                if (cssElement.length === 0) {
                    cssElement = jQuery('<style>', { id: 'dracula-custom-css' }).appendTo('body');
                }

                cssElement.html(compiledCss);
            }
        } catch (error) {
            console.log(error)
        }

    }, [customCss]);

    useEffect(() => {
        if (!isMounted || !isLiveEdit) return;

        try {
            let cssElement = jQuery('#dracula-custom-css');
            if (cssElement.length === 0) {
                cssElement = jQuery('<style>', { id: 'dracula-custom-css' }).appendTo('body');
            }

            cssElement.html(lightModeCSS);
        } catch (error) {
            console.log(error)
        }

    }, [lightModeCSS]);

    return (
        <div className="dracula-settings-content">
            <Header title={wp.i18n.__('Custom CSS', 'dracula-dark-mode')} />

            {/* Light Mode CSS */}
            <div className={`settings-field custom-css ${!isPro ? 'pro-feature' : ''}`}>
                <h4 className={`settings-field-label`}>
                    {wp.i18n.__('Normal Mode CSS', 'dracula-dark-mode')}
                    {!isPro && <span className="dracula-pro-icon"><i className={`dracula-icon icon-pro`}/></span>}
                </h4>
                <div className="settings-field-content">
                    {!isLiveEdit && <LiveEditButton tab="css" />}

                    <p className="description">{wp.i18n.__('Add normal mode CSS here. This CSS will be applied both in light and dark mode.', 'dracula-dark-mode')}</p>

                    <div className="settings-wrap"
                        data-tooltip-id={`light-mode-css`}
                        data-tooltip-content={!isPro ? wp.i18n.__('PRO Feature', 'dracula-dark-mode') : ''}
                        onClick={() => !isPro && showProModal(wp.i18n.__('Upgrade to PRO to unlock custom CSS feature.', 'dracula-dark-mode'))}
                    >
                        <textarea
                            value={lightModeCSS}
                            onChange={(value) => setData({ ...data, lightModeCSS: value.target.value })}
                            placeholder="Enter your custom CSS here..."
                            className="dracula-custom-css-editor editor-light-mode"
                            rows={isLiveEdit ? 10 : 20}
                        />
                    </div>

                    {!isPro && <Tooltip id={`light-mode-css`} variant="warning" effect="solid" place="left" backgroundColor="#ff9966" className={'dracula-tooltip'} />}

                </div>
            </div>

            {/* Dark Mode CSS */}
            <div className={`settings-field custom-css ${!isPro ? 'pro-feature' : ''} field-dark-mode-css`}>
                <h4 className={`settings-field-label`}>
                    {wp.i18n.__('Dark Mode CSS', 'dracula-dark-mode')}
                    {!isPro && <span className="dracula-pro-icon"><i className={`dracula-icon icon-pro`}/></span>}
                </h4>
                <div className="settings-field-content">
                    {!isLiveEdit && <LiveEditButton tab="css" />}

                    <p className="description">
                        {wp.i18n.__('Add Dark Mode CSS here. This CSS will be applied only when the dark mode is activated.', 'dracula-dark-mode')}
                        <br />
                        {wp.i18n.__('You don\'t need to add any dark mode prefix selectors here. It will be added automatically.', 'dracula-dark-mode')}
                    </p>

                    <div className="settings-wrap"
                        data-tooltip-id={`dark-mode-css`}
                        data-tooltip-content={!isPro ? wp.i18n.__('PRO Feature', 'dracula-dark-mode') : ''}
                        onClick={() => !isPro && showProModal(wp.i18n.__('Upgrade to PRO to unlock custom CSS feature.', 'dracula-dark-mode'))}
                    >
                        <textarea
                            value={customCss}
                            onChange={(value) => setData({ ...data, customCss: value.target.value })}
                            placeholder="Enter your custom CSS here..."
                            className="dracula-custom-css-editor"
                            rows={isLiveEdit ? 10 : 20}
                        />
                    </div>

                    {!isPro && <Tooltip id={`dark-mode-css`} variant="warning" effect="solid" place="left" backgroundColor="#ff9966" className={'dracula-tooltip'} />}
                </div>
            </div>


        </div>
    )
}