import preloaders from "../../includes/preloaders";

import {Tooltip} from "react-tooltip";
import {showProModal} from "../../includes/ProModal";
import {colorBrightness, hex2Rgba} from "../../includes/functions";

const {
    ColorPalette,
} = wp.components;

const {useEffect, useRef} = React;

export default function Appearance({data, setData}) {

    const {isPro} = igd;

    const {
        preloader = 'default',
        customPreloader,
        primaryColor = '#3C82F6',
        customCss,
    } = data;

    useEffect(() => {
        const cssEditor = document.querySelector('.igd-custom-css');

        if (!cssEditor) return;

        const instance = wp.codeEditor?.initialize(cssEditor, {
            ...wp.codeEditor.defaultSettings,
            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();
            setData({...data, customCss: value});
        });

    }, []);

    const frameRef = useRef();

    const uploadPreloader = () => {

        if (frameRef.current) {
            frameRef.current.off('select');

            frameRef.current.on('select', () => {
                const attachment = frameRef.current.state().get('selection').first().toJSON();

                setData({...data, customPreloader: attachment.url});

            }).open();
            return;
        }

        frameRef.current = wp.media({
            title: wp.i18n.__('Select Preloader', 'integrate-google-drive'),
            button: {text: wp.i18n.__('Select', 'integrate-google-drive')},
            multiple: false,
            library: {type: 'image'},
        });

        frameRef.current.on('select', () => {
            const attachment = frameRef.current.state().get('selection').first().toJSON();
            setData({...data, customPreloader: attachment.url});
        }).open();
    }

    // Handle css variables
    useEffect(() => {
        document.documentElement.style.setProperty('--color-primary', primaryColor);
        document.documentElement.style.setProperty('--color-primary-dark', colorBrightness(primaryColor, -30));
        document.documentElement.style.setProperty('--color-primary-light', hex2Rgba(primaryColor, .5));
        document.documentElement.style.setProperty('--color-primary-light-alt', colorBrightness(primaryColor, 30));
        document.documentElement.style.setProperty('--color-primary-lighter', hex2Rgba(primaryColor, .1));
        document.documentElement.style.setProperty('--color-primary-lighter-alt', colorBrightness(primaryColor, 50));

    }, [primaryColor]);

    return (
        <div className="igd-settings-body">
            <div className="igd-settings-body-header">
                <h3 className="igd-settings-body-title">{wp.i18n.__('Appearance Settings', 'integrate-google-drive')}</h3>
                <p>{wp.i18n.__('Customize the appearance of the shortcode modules and plugin interface.', 'integrate-google-drive')}</p>
            </div>

            {/* Preloader */}
            <div className="settings-field field-preloader">
                <h4 className="settings-field-label">{wp.i18n.__('Preloader', 'integrate-google-drive')}</h4>
                <p className="description">{wp.i18n.__('Choose the preloader style for the file browser. Preloader will be displayed in the file browser while the files are loading.', 'integrate-google-drive')}</p>

                <div className="settings-field-content">

                    <div className="preloaders">

                        <div
                            className={`preloader preloader-none ${preloader === 'none' && !customPreloader ? 'active' : ''}`}
                            onClick={() => setData({...data, preloader: 'none', customPreloader: ''})}>

                            <span className={`preloader-title`}>{wp.i18n.__('None', 'integrate-google-drive')}</span>

                            <span className="preloader-name">{wp.i18n.__('None', 'integrate-google-drive')}</span>
                        </div>

                        {Object.keys(preloaders).map(key => {

                            const item = preloaders[key];

                            const isActive = (isPro || ['default', 'ring'].includes(key)) && preloader === key && !customPreloader;

                            return (
                                <div
                                    className={`preloader ${isActive ? 'active' : ''} ${!isPro && !['default', 'ring'] ? 'disabled' : ''}`}
                                    key={key}
                                    onClick={() => {
                                        if (!isPro && !['default', 'ring'].includes(key)) {
                                            showProModal(wp.i18n.__(`Upgrade to PRO to use this preloader.`, 'integrate-google-drive'));
                                            return;
                                        }

                                        setData({...data, preloader: key, customPreloader: ''});
                                    }}>

                                    <span dangerouslySetInnerHTML={{__html: item.svg}}/>

                                    {(!isPro && !['default', 'ring'].includes(key)) ?
                                        <div className="preloader-name">
                                            <i className="igd-icon icon-pro"></i>
                                            <span>{wp.i18n.__('PRO', 'integrate-google-drive')}</span>
                                        </div>
                                        :
                                        <div className="preloader-name">
                                            <span>{item.title}</span>
                                        </div>
                                    }
                                </div>
                            )
                        })}
                    </div>

                    <div className="preloader-upload">
                        <h4>{wp.i18n.__('Custom Preloader Image', 'integrate-google-drive')}</h4>

                        <div className="preloader-upload-actions">

                            <button
                                data-tooltip-content={wp.i18n.__("PRO Feature", "integrate-google-drive")}
                                data-tooltip-id={`igd-pro-tooltip`}
                                type={`button`}
                                className={`igd-btn btn-info upload-btn ${!isPro ? 'disabled' : ''}`}
                                onClick={() => {
                                    if (!isPro) {
                                        showProModal(wp.i18n.__(`Upgrade to PRO to use custom preloader.`, 'integrate-google-drive'));
                                        return;
                                    }

                                    uploadPreloader();
                                }}
                            >
                                <i className="dashicons dashicons-upload"></i>
                                <span>{wp.i18n.__('Upload Image', 'integrate-google-drive')}</span>

                                {!isPro &&
                                    <span className={`igd-pro-icon`}>
                                        <i className="igd-icon icon-pro"></i>
                                    </span>
                                }

                            </button>

                            {!isPro &&
                                <Tooltip
                                    id={"igd-pro-tooltip"}
                                    effect={"solid"}
                                    place={"right"}
                                    variant={"warning"}
                                    className={"igd-tooltip"}
                                />
                            }

                            {!!customPreloader &&
                                <button type={`button`} className={`igd-btn btn-danger`}
                                        onClick={() => setData({...data, customPreloader: ''})}
                                >
                                    <i className="dashicons dashicons-trash"></i>
                                    <span>{wp.i18n.__('Remove', 'integrate-google-drive')}</span>
                                </button>
                            }
                        </div>

                        {!!customPreloader &&
                            <div className="preloader-preview">
                                <img src={customPreloader}
                                     alt={wp.i18n.__("Custom preloader preview", "integrate-google-drive")}/>
                            </div>
                        }
                    </div>

                </div>
            </div>

            {/* Theme Color */}
            <div className="settings-field">
                <h4 className="settings-field-label">
                    {wp.i18n.__('Theme Color', 'integrate-google-drive')}

                    {!isPro && <span className={`igd-pro-icon`}><i className="igd-icon icon-pro"></i></span>}

                </h4>

                <div className="settings-field-content">

                    <div className="igd-color-palette-wrap"
                         data-tooltip-content={wp.i18n.__("PRO Feature", 'integrate-google-drive')}
                         data-tooltip-id={`primary-color-tooltip`}
                         onClick={() => {
                             if (!isPro) {
                                 showProModal(wp.i18n.__(`Upgrade to PRO to change the plugin theme color.`, 'integrate-google-drive'));
                             }
                         }}
                    >
                        <ColorPalette
                            colors={[
                                {name: 'Default', color: '#3C82F6'},
                                {name: 'Green', color: '#2FB44B'},
                                {"color": "#2463EB", "name": "Azure"},
                                {"color": "#0073aa", "name": "Sapphire Blue"},
                                {"color": "#2265C0", "name": "Lapis Blue"},
                                {"color": "#3F51B5", "name": "Indigo"},
                                {"color": "#6E61C2", "name": "Amethyst"}
                            ]}
                            value={primaryColor}
                            onChange={primaryColor => {
                                if (!isPro) {
                                    showProModal(wp.i18n.__(`Upgrade to PRO to change the plugin theme color.`, 'integrate-google-drive'));
                                    return;
                                }

                                setData({...data, primaryColor})
                            }}
                            className={`igd-color-palette ${isPro ? '' : 'disabled'}`}
                            enableAlpha={true}
                            asButtons={true}
                        />
                    </div>

                    <p className="description">{wp.i18n.__('Choose the theme color for the plugin. The color affects both the admin and frontend modules.', 'integrate-google-drive')}</p>
                </div>
            </div>

            {/* Custom CSS */}
            <div className="settings-field field-custom-css">
                <h4 className="settings-field-label">{wp.i18n.__('Custom CSS', 'integrate-google-drive')}</h4>
                <p className="description">{wp.i18n.__('To customize the plugin\'s styles, insert your custom CSS here.', 'integrate-google-drive')}</p>

                <div className="settings-field-content">

                    <textarea
                        value={customCss}
                        onChange={customCss => setData({...data, customCss})}
                        rows={20}
                        placeholder={wp.i18n.__("Enter your custom CSS here...", 'integrate-google-drive')}
                        id="igd-custom-css"
                        className={`igd-textarea igd-custom-css`}
                    />

                </div>
            </div>

        </div>
    )
}
