import {Tooltip} from "react-tooltip";
import Select from "react-select";
import SelectElements from "../LiveEdit/SelectElements";
import SelectHides from "../LiveEdit/SelectHides";
import SettingsContext from "../../contexts/SettingsContext";
import Header from "./Header";
import {getConfig} from "../../includes/functions";
import LiveEditButton from "./LiveEditButton";
import {showProModal} from "../ProModal";

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

export default function Excludes() {
    const {isPro} = dracula;

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

    const excludeList = [];
    const excludeTaxList = [];

    if (!isLiveEdit) {

        Object.keys(dracula.excludeList).forEach(key => {
            const options = dracula.excludeList[key].options;
            excludeList.push({
                label: dracula.excludeList[key].label,
                options: Object.keys(options).map(key => {
                    return {
                        label: options[key],
                        value: key,
                    };
                })
            });
        });

        Object.keys(dracula.excludeTaxList).forEach(key => {
            const options = dracula.excludeTaxList[key].options;
            excludeTaxList.push({
                label: dracula.excludeTaxList[key].label,
                options: Object.keys(options).map(key => {
                    return {
                        label: options[key],
                        value: key,
                    };
                })
            });
        });
    }

    const {
        excludes = [''],
        excludePages = [],
        excludeAll = false,
        excludeExceptPages = [],
        excludeTaxs = [],
        excludeAllTaxs = false,
        excludeExceptTaxs = [],
        hides = [''],
    } = data;

    const [currentExclude, setCurrentExclude] = useState(null);
    const [currentHide, setCurrentHide] = useState(null);

    useEffect(() => {

        if (!hides.length) {
            let element = document.getElementById('dracula-hides-css');
            if (element) {
                element.remove();
            }

            return;
        }

        let css = '';

        hides.forEach((selector) => {
            css += `${selector} { display: none !important; }\n`;
        });

        let element = document.getElementById('dracula-hides-css');
        if (!element) {
            element = document.createElement('style');
            element.id = 'dracula-hides-css';

            document.head.appendChild(element);
        }

        element.innerHTML = css;

    }, [hides])

    return (
        <div className="dracula-settings-content">


            <Header title={wp.i18n.__('Excludes Settings', 'dracula-dark-mode')}/>

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

                        <div className="settings-wrap"
                            data-tooltip-id="exclude-pages"
                             data-tooltip-content={!isPro ? wp.i18n.__('PRO Feature', 'dracula-dark-mode') : ''}
                             onClick={() => !isPro && showProModal(wp.i18n.__('Exclude Pages is a PRO feature. Please upgrade to PRO version to use this feature.', 'dracula-dark-mode'))}>
                            <Select
                                isDisabled={!isPro || excludeAll}
                                isMulti={true}
                                options={excludeList}
                                className={'dracula-select'}
                                classNamePrefix={'dracula-select'}
                                onChange={selected => {
                                    if (!isPro) {
                                        showProModal();
                                        return;
                                    }
                                    setData({...data, excludePages: selected.map(item => item.value)})
                                }}
                                value={
                                    !!excludeList.length &&
                                    excludePages.map(item => {
                                        // Find the group and item to reconstruct the label with the group name
                                        let itemLabel = '';
                                        let groupLabel = '';
                                        for (const group of excludeList) {
                                            const foundOption = group.options.find(option => option.value === item);
                                            if (foundOption) {
                                                itemLabel = foundOption.label;
                                                groupLabel = group.label;
                                                break; // Exit loop once found
                                            }
                                        }
                                        // Construct the value with a textual badge (group label), without color differentiation
                                        return {
                                            value: item,
                                            label: `${itemLabel} [${groupLabel}]`, // Example format: "Item Label [Group Label]"
                                        };
                                    })
                                }
                                placeholder={wp.i18n.__('Search & select posts/ pages', 'dracula-dark-mode')}
                            />
                        </div>

                        {!isPro && <Tooltip id="exclude-pages" variant="warning" effect="solid" place="right" backgroundColor="#ff9966" className={'dracula-tooltip'}/>}

                        <p className="description">{wp.i18n.__('Select posts, pages, and custom post types to exclude from dark mode.', 'dracula-dark-mode')}</p>

                        <div className="excludes-except">
                            <span className="exclude-all-label">{wp.i18n.__('Exclude All : ', 'dracula-dark-mode')}</span>

                            <FormToggle
                                data-tooltip-id="exclude-all"
                                data-tooltip-content={!isPro ? wp.i18n.__('PRO Feature', 'dracula-dark-mode') : ''}
                                checked={excludeAll}
                                onChange={() => {
                                    if (!isPro) {
                                        showProModal(wp.i18n.__('Exclude Pages is a PRO feature. Please upgrade to PRO version to use this feature.', 'dracula-dark-mode'));
                                        return;
                                    }

                                    setData({...data, excludeAll: !excludeAll})
                                }}
                            />

                            { !isPro && <Tooltip id="exclude-all" variant="warning" effect="solid" place="right" backgroundColor="#ff9966" className={'dracula-tooltip'}/> }

                            <span className="exclude-except-label"> {wp.i18n.__('Except : ', 'dracula-dark-mode')}</span>

                            <div className="settings-wrap"
                                 data-tooltip-id="exclude-except-pages"
                                 data-tooltip-content={!isPro ? wp.i18n.__('PRO Feature', 'dracula-dark-mode') : ''}
                                 onClick={() => !isPro && showProModal(wp.i18n.__('Exclude Pages is a PRO feature. Please upgrade to PRO version to use this feature.', 'dracula-dark-mode'))}>
                                <Select
                                    isMulti={true}
                                    options={excludeList}
                                    className={'dracula-select'}
                                    classNamePrefix={'dracula-select'}
                                    onChange={selected => {
                                        setData({...data, excludeExceptPages: selected.map(item => item.value)})
                                    }}

                                    value={
                                        !!excludeList.length &&
                                        excludeExceptPages.map(item => {
                                            // Find the group and item to reconstruct the label with the group name
                                            let itemLabel = '';
                                            let groupLabel = '';
                                            for (const group of excludeList) {
                                                const foundOption = group.options.find(option => option.value === item);
                                                if (foundOption) {
                                                    itemLabel = foundOption.label;
                                                    groupLabel = group.label;
                                                    break; // Exit loop once found
                                                }
                                            }
                                            // Construct the value with a textual badge (group label), without color differentiation
                                            return {
                                                value: item,
                                                label: `${itemLabel} [${groupLabel}]`, // Example format: "Item Label [Group Label]"
                                            };
                                        })
                                    }
                                    placeholder={wp.i18n.__('Search and select posts/pages', 'dracula-dark-mode')}
                                    isDisabled={!isPro || !excludeAll}
                                />
                            </div>

                            {!isPro && <Tooltip id="exclude-except-pages" variant="warning" effect="solid" place="right" backgroundColor="#ff9966" className={'dracula-tooltip'}/>}
                        </div>

                    </div>
                </div>
            }

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

                        <div className="settings-wrap"
                             data-tooltip-id="exclude-taxonomies"
                             data-tooltip-content={!isPro ? wp.i18n.__('PRO Feature', 'dracula-dark-mode') : ''}
                             onClick={() => !isPro && showProModal(wp.i18n.__('Exclude Taxonomies is a PRO feature. Please upgrade to PRO version to use this feature.', 'dracula-dark-mode'))}>
                            <Select
                                isDisabled={!isPro || excludeAllTaxs}
                                isMulti={true}
                                options={excludeTaxList}
                                className={'dracula-select'}
                                classNamePrefix={'dracula-select'}
                                onChange={selected => {
                                    if (!isPro) {
                                        showProModal();
                                        return;
                                    }
                                    setData({...data, excludeTaxs: selected.map(item => item.value)})
                                }}
                                placeholder={wp.i18n.__('Search & select categories/ tags', 'dracula-dark-mode')}

                                value={
                                    !!excludeTaxList.length &&
                                    excludeTaxs.map(item => {
                                        // Find the group and item to reconstruct the label with the group name
                                        let itemLabel = '';
                                        let groupLabel = '';
                                        for (const group of excludeTaxList) {
                                            const foundOption = group.options.find(option => option.value === item);
                                            if (foundOption) {
                                                itemLabel = foundOption.label;
                                                groupLabel = group.label;
                                                break; // Exit loop once found
                                            }
                                        }
                                        // Construct the value with a textual badge (group label), without color differentiation
                                        return {
                                            value: item,
                                            label: `${itemLabel} [${groupLabel}]`, // Example format: "Item Label [Group Label]"
                                        };
                                    })
                                }

                            />
                        </div>

                        {!isPro && <Tooltip id="exclude-taxonomies" variant="warning" effect="solid" place="right" backgroundColor="#ff9966" className={'dracula-tooltip'}/>}

                        <p className="description">{wp.i18n.__('Select categories, tags, and taxonomies to omit posts from dark mode.', 'dracula-dark-mode')}</p>

                        <div className="excludes-except">
                            <span
                                className="exclude-all-label">{wp.i18n.__('Exclude All : ', 'dracula-dark-mode')}</span>

                            <FormToggle
                                disabled={!isPro}
                                data-tooltip-id="exclude-except-taxonomies"
                                data-tooltip-content={!isPro ? wp.i18n.__('PRO Feature', 'dracula-dark-mode') : ''}
                                checked={excludeAllTaxs}
                                onChange={() => {
                                    if (!isPro) {
                                        showProModal(wp.i18n.__('Exclude Taxonomies is a PRO feature. Please upgrade to PRO version to use this feature.', 'dracula-dark-mode'));
                                        return;
                                    }

                                    setData({...data, excludeAllTaxs: !excludeAllTaxs})
                                }}
                            />

                            {!isPro && <Tooltip id="exclude-except-taxonomies" variant="warning" effect="solid" place="right" backgroundColor="#ff9966" className={'dracula-tooltip'}/>}

                            <span
                                className="exclude-except-label"> {wp.i18n.__('Except : ', 'dracula-dark-mode')}</span>

                            <div className="settings-wrap"
                                 data-tooltip-id="exclude-except-taxonomies"
                                 data-tooltip-content={!isPro ? wp.i18n.__('PRO Feature', 'dracula-dark-mode') : ''}
                                 onClick={() => !isPro && showProModal(wp.i18n.__('Exclude Pages is a PRO feature. Please upgrade to PRO version to use this feature.', 'dracula-dark-mode'))}>
                                <Select
                                    isMulti={true}
                                    options={excludeTaxList}
                                    className={'dracula-select'}
                                    classNamePrefix={'dracula-select'}
                                    onChange={selected => {
                                        setData({...data, excludeExceptTaxs: selected.map(item => item.value)})
                                    }}
                                    value={
                                        !!excludeTaxList.length &&
                                        excludeExceptTaxs.map(item => {
                                            // Find the group and item to reconstruct the label with the group name
                                            let itemLabel = '';
                                            let groupLabel = '';
                                            for (const group of excludeTaxList) {
                                                const foundOption = group.options.find(option => option.value === item);
                                                if (foundOption) {
                                                    itemLabel = foundOption.label;
                                                    groupLabel = group.label;
                                                    break; // Exit loop once found
                                                }
                                            }
                                            // Construct the value with a textual badge (group label), without color differentiation
                                            return {
                                                value: item,
                                                label: `${itemLabel} [${groupLabel}]`, // Example format: "Item Label [Group Label]"
                                            };
                                        })
                                    }
                                    placeholder={wp.i18n.__('Search and select category/ tags', 'dracula-dark-mode')}
                                    isDisabled={!isPro || !excludeAllTaxs}
                                />
                            </div>

                            {!isPro && <Tooltip id="exclude-except-taxonomies" variant="warning" effect="solid" place="right" backgroundColor="#ff9966" className={'dracula-tooltip'}/>}
                        </div>

                    </div>
                </div>
            }

            {/* Exclude Element */}
            <div className={`settings-field ${!isPro ? 'pro-feature' : ''}`}>
                <h4 className={`settings-field-label`}>
                    {wp.i18n.__('Exclude Elements', '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={'excludes'}/>}

                    <div className="excludes">
                        {!!isPro && excludes.map((item, index) => {
                            return (
                                <div className={`exclude-item`}>

                                    <input
                                        type="text"
                                        value={item}
                                        onChange={e => {
                                            setCurrentExclude(index);

                                            const newExcludes = [...excludes];
                                            newExcludes[index] = e.target.value;
                                            setData({...data, excludes: newExcludes});
                                        }}
                                        placeholder={'CSS Selector (Class or ID)'}
                                    />

                                    {(currentExclude === index && isLiveEdit) ?
                                        <button type="button" className="dracula-btn btn-primary save-exclude"
                                                onClick={() => {
                                                    setCurrentExclude(null);

                                                    if (isLiveEdit && draculaDarkMode.isEnabled()) {
                                                        draculaDarkMode.disable();
                                                        draculaDarkMode.enable(getConfig(data));
                                                    }

                                                }}>
                                            <i className="dashicons dashicons-saved"></i>
                                        </button>
                                        :
                                        <button type="button" className="dracula-btn btn-danger remove-exclude"
                                                onClick={() => {
                                                    const newExcludes = [...excludes];
                                                    newExcludes.splice(index, 1);

                                                    const newData = {...data, excludes: newExcludes};
                                                    setData(newData);

                                                    if (isLiveEdit && draculaDarkMode.isEnabled()) {
                                                        draculaDarkMode.disable();
                                                        draculaDarkMode.enable(getConfig(newData));
                                                    }

                                                }}>
                                            <i className="dashicons dashicons-no-alt"></i>
                                        </button>
                                    }
                                </div>
                            );
                        })
                        }

                        <button
                            type="button"
                            disabled={!isPro}
                            data-tooltip-id={'exclude-exclude'}
                            data-tooltip-content={!isPro ? wp.i18n.__('PRO Feature', 'dracula-dark-mode') : ''}
                            className="dracula-btn btn-primary add-exclude"
                            onClick={() => {
                                if (!isPro) {
                                    showProModal();
                                    return;
                                }

                                setData({...data, excludes: [...excludes, '']});
                                setCurrentExclude(excludes.length);
                            }}>
                            <i className="dashicons dashicons-plus-alt2"></i>
                            <span>{wp.i18n.__('Add Element', 'dracula-dark-mode')}</span>
                        </button>

                        {!isPro && <Tooltip id="exclude-exclude" variant="warning" effect="solid" place="right" backgroundColor="#ff9966" className={'dracula-tooltip'}/>}

                    </div>

                    {!!isLiveEdit && 'classic' !== isEditor && <SelectElements data={data} setData={setData}/>}

                    <p className="description">
                        {wp.i18n.__('Exclude specific sections/ elements in a page from dark mode. You can use CSS selectors or HTML tags to exclude elements.', 'dracula-dark-mode')}
                    </p>

                </div>
            </div>

            {/* Hide Element */}
            <div className={`settings-field ${!isPro ? 'pro-feature' : ''}`}>
                <h4 className={`settings-field-label`}>
                    {wp.i18n.__('Hide Elements', '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={'excludes'}/>}

                    <div className="excludes">
                        {!!isPro && hides.map((item, index) => {
                            return (
                                <div className={`exclude-item`}>
                                    <input type="text" value={item} onChange={e => {
                                        setCurrentHide(index);

                                        const newHides = [...hides];
                                        newHides[index] = e.target.value;
                                        setData({...data, hides: newHides});
                                    }} placeholder={'CSS Selector (Class or ID)'}/>

                                    {(currentHide === index && isLiveEdit) ?
                                        <button type="button" className="dracula-btn btn-primary save-exclude"
                                                onClick={() => {
                                                    setCurrentHide(null);

                                                    if (isLiveEdit && draculaDarkMode.isEnabled()) {
                                                        draculaDarkMode.disable();
                                                        draculaDarkMode.enable(getConfig(data));
                                                    }

                                                }}>
                                            <i className="dashicons dashicons-saved"></i>
                                        </button>
                                        :
                                        <button type="button" className="dracula-btn btn-danger remove-exclude"
                                                onClick={() => {
                                                    const newHides = [...hides];
                                                    newHides.splice(index, 1);

                                                    const newData = {...data, hides: newHides};
                                                    setData(newData);

                                                    if (isLiveEdit && draculaDarkMode.isEnabled()) {
                                                        draculaDarkMode.disable();
                                                        draculaDarkMode.enable(getConfig(newData));
                                                    }

                                                }}>
                                            <i className="dashicons dashicons-no-alt"></i>
                                        </button>
                                    }
                                </div>
                            );
                        })
                        }

                        <button
                            type="button"
                            disabled={!isPro}
                            data-tooltip-id={'exclude-exclude'}
                            data-tooltip-content={!isPro ? wp.i18n.__('PRO Feature', 'dracula-dark-mode') : ''}
                            className="dracula-btn btn-primary add-exclude"
                            onClick={() => {
                                if (!isPro) {
                                    showProModal();
                                    return;
                                }

                                setData({...data, hides: [...hides, '']});
                                setCurrentHide(hides.length);
                            }}>
                            <i className="dashicons dashicons-plus-alt2"></i>
                            <span>{wp.i18n.__('Add Element', 'dracula-dark-mode')}</span>
                        </button>

                        {!isPro && <Tooltip id="exclude-exclude" variant="warning" effect="solid" place="right" backgroundColor="#ff9966" className={'dracula-tooltip'}/>}

                    </div>

                    {!!isLiveEdit && 'classic' !== isEditor && <SelectHides data={data} setData={setData}/>}

                    <p className="description">
                        {wp.i18n.__('Hide specific sections/ elements in a page/post. You can use CSS selectors to hide elements.', 'dracula-dark-mode')}
                    </p>
                </div>
            </div>

        </div>
    )
}