import {Tooltip} from "react-tooltip";
import {showProModal} from "../../includes/functions";

const {RangeControl, FormToggle, SelectControl} = wp.components;

const {useEffect} = React;

export default function PopupSettings({data, setData}) {
    const {isPro, players} = radioPlayer;

    const playerList = [];

    if (isPro) {
        players.map(item => {
            playerList.push({value: item.id, label: item.title});
        });
    } else {
        playerList.push({label: wp.i18n.__(`Select Player`, "radio-player"), value: 0});
    }

    const {
        alwaysPopup,
        customPopupSize,
        popupWidth = 450,
        popupHeight = 550,

        popupHeaderContent,
        popupFooterContent,

        popupTriggers = isPro ? [] : [{}],
    } = data;

    useEffect(() => {
        const config = {
            tinymce: {
                wpautop: true,
                toolbar1: 'formatselect,bold,italic,strikethrough,forecolor,backcolor,bullist,numlist,blockquote,hr,alignleft,aligncenter,alignright,link,unlink,media,spellchecker,fullscreen,wp_adv',
                toolbar2: 'underline,alignjustify,forecolor,pastetext,removeformat,charmap,outdent,indent,undo,redo,wp_help',
                plugins: 'lists,fullscreen, paste, wpautoresize, wpdialogs, wpeditimage, wpgallery, wplink, wptextpattern, wpview, wordpress, wpemoji,media,textcolor,hr',
                menubar: false,
                branding: false,
                height: 250,
                wp_adv_height: 48,
                setup: function (editor) {
                    const id = editor.id;

                    editor.on('change', function () {

                        if (!isPro) {
                            showProModal(wp.i18n.__('Upgrade to PRO to use the popup player.', 'radio-player'));
                            return;
                        }

                        const content = editor.getContent();

                        if (id === 'header-content-editor') {
                            setData(prev => ({...prev, popupHeaderContent: content}));
                        } else if (id === 'footer-content-editor') {
                            setData(prev => ({...prev, popupFooterContent: content}));
                        }

                    });

                }
            },
            quicktags: {
                buttons: 'strong,em,link,block,del,ins,img,ul,ol,li,code,close',
            },
            mediaButtons: true,
        };

        setTimeout(() => {
            ['header-content-editor', 'footer-content-editor'].forEach(id => {
                wp.editor.initialize(id, config);
            });

        }, 500);

        return () => {
            ['header-content-editor', 'footer-content-editor'].forEach(id => {
                if (document.getElementById(id)) {
                    wp.editor.remove(id);
                }
            });
        }

    }, []);

    const updateTrigger = (index, key, value) => {
        setData({
            ...data,
            popupTriggers: [...popupTriggers.slice(0, index), {
                ...popupTriggers[index],
                [key]: value
            }, ...popupTriggers.slice(index + 1)]
        });
    }

    const removeTrigger = (index) => {
        const newTriggers = [...popupTriggers.slice(0, index), ...popupTriggers.slice(index + 1)];

        setData({...data, popupTriggers: newTriggers});
    }

    return (
        <div className="tab-content">

            <div className="settings-header">
                <img src={`${radioPlayer.plugin_url}/assets/images/settings/popup.svg`}/>

                <span>{wp.i18n.__('Popup Settings', 'radio-player')}</span>
            </div>

            {/* Always Popup */}
            <div className="setting-field">

                <h4 className={`setting-field-label`}>
                    {wp.i18n.__('Always Popup', 'radio-player')}
                    {!isPro &&
                        <span className="radio-player-pro-icon">
                            <i className={`radio-player-icon icon-pro`}/>
                        </span>
                    }
                </h4>

                <div className={`setting-field-content `}>

                    <div className={`${!isPro ? 'pro-disabled' : ''} input-group`}>
                        <FormToggle
                            checked={isPro && alwaysPopup}
                            onChange={() => {

                                if (!isPro) {
                                    showProModal(wp.i18n.__('Upgrade to PRO to use the popup player.', 'radio-player'));
                                    return;
                                }

                                setData(data => ({...data, alwaysPopup: !alwaysPopup}))
                            }}
                        />
                    </div>

                    <p className="description">{wp.i18n.__('Turn it ON to play the player always in the popup window when the user clicks on the play button.', 'radio-player')}</p>
                </div>

            </div>

            {/* Custom Popup Size */}
            <div className="setting-field">
                <h4 className={`setting-field-label`}>
                    {wp.i18n.__('Customize Popup Player Size', 'radio-player')}
                    {!isPro &&
                        <span className="radio-player-pro-icon">
                            <i className={`radio-player-icon icon-pro`}/>
                        </span>
                    }
                </h4>

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

                    <div className={`${!isPro ? 'pro-disabled' : ''} input-group`}>
                        <FormToggle
                            checked={isPro && !!customPopupSize}
                            onChange={() => {

                                if (!isPro) {
                                    showProModal(wp.i18n.__('Upgrade to PRO to customize the popup player size.', 'radio-player'));
                                    return;
                                }

                                setData(data => ({...data, customPopupSize: !customPopupSize,}));
                            }}
                        />
                    </div>

                    <p className="description">{wp.i18n.__('Turn ON to customize the popup player width and height.', 'radio-player')}</p>
                </div>

            </div>

            {(!isPro || !!customPopupSize) &&
                <div className="setting-field popup-size">

                    <h4 className={`setting-field-label`}>
                        {wp.i18n.__('Popup Player Size', 'radio-player')}
                        {!isPro &&
                            <span className="radio-player-pro-icon">
                            <i className={`radio-player-icon icon-pro`}/>
                        </span>
                        }
                    </h4>

                    <div className="setting-field-content">
                        <RangeControl
                            className={`radio-player-range-control ${!isPro ? 'pro-disabled' : ''}`}
                            label={wp.i18n.__("Player Width", 'radio-player')}
                            value={popupWidth}
                            onChange={(popupWidth) => {

                                if (!isPro) {
                                    showProModal(wp.i18n.__('Upgrade to PRO to customize the popup player size.', 'radio-player'));
                                    return;
                                }

                                setData(data => ({...data, popupWidth}))
                            }}
                            min={100}
                            max={1000}
                            step={5}
                            allowReset={true}
                            resetFallbackValue={400}
                        />

                        <RangeControl
                            className={`radio-player-range-control ${!isPro ? 'pro-disabled' : ''}`}
                            label={wp.i18n.__("Player Height", 'radio-player')}
                            value={popupHeight}
                            onChange={(popupHeight) => {
                                if (!isPro) {
                                    showProModal(wp.i18n.__('Upgrade to PRO to customize the popup player size.', 'radio-player'));
                                    return;
                                }
                                setData(data => ({...data, popupHeight}))
                            }}
                            min={100}
                            max={1000}
                            step={5}
                            allowReset={true}
                            resetFallbackValue={600}
                        />

                    </div>
                </div>
            }

            {/* Popup Triggers */}
            <div className="setting-field field-popup-triggers">

                <div className="setting-field-content">
                    <div className="popup-triggers">
                        <h3>
                            {wp.i18n.__('Custom Popup Triggers', 'radio-player')}
                            {!isPro &&
                                <span className="radio-player-pro-icon">
                                    <i className={`radio-player-icon icon-pro`}/>
                                </span>
                            }
                        </h3>

                        <p>{wp.i18n.__('Allow any element on your website to open and play any player in the popup player mode when clicked.', 'radio-player')}</p>

                        {popupTriggers.map((triger, index) => {
                            const {selector, player} = triger;

                            return (
                                <div
                                    className={`trigger-group ${!isPro ? 'pro-disabled' : ''}`}
                                    onClick={() => {
                                        if (!isPro) {
                                            showProModal();
                                        }
                                    }}
                                    key={index}
                                >
                                    <div className="group-item">

                                        {index === 0 &&
                                            <div className={`group-item-header`}>
                                                <span
                                                    className={`header-title`}>{wp.i18n.__('Element Selector', 'radio-player')}</span>
                                            </div>
                                        }

                                        <div className="input-group">
                                            <input type="text" placeholder="Enter CSS Selector (e.g. .my-class, #my-id)"
                                                   value={selector}
                                                   onChange={e => updateTrigger(index, 'selector', e.target.value)}/>
                                        </div>
                                    </div>

                                    {/* Player */}
                                    <div className="group-item">

                                        {index === 0 &&
                                            <div className={`group-item-header`}>
                                            <span
                                                className={`header-title`}>{wp.i18n.__('Select Player', 'radio-player')}</span>
                                            </div>
                                        }

                                        <div className="input-group">

                                            <SelectControl
                                                isDisabled={!isPro}
                                                value={player}
                                                options={playerList}
                                                onChange={value => {

                                                    if (!isPro) {
                                                        showProModal(wp.i18n.__('Upgrade to PRO to use the Popup Player.', 'radio-player'));
                                                        return;
                                                    }

                                                    updateTrigger(index, 'player', value);
                                                }}
                                                __next40pxDefaultSize={true}
                                                __nextHasNoMarginBottom={true}

                                            />

                                        </div>

                                    </div>


                                    <button type={`button`} className="radio-player-btn btn-danger"
                                            onClick={() => removeTrigger(index)}>
                                        <i className="dashicons dashicons-trash"></i>
                                    </button>

                                </div>
                            )
                        })}

                        <button
                            type={`button`}
                            className={`radio-player-btn add-group ${!isPro ? 'pro-disabled' : ''}`}
                            onClick={() => {

                                if (!isPro) {
                                    showProModal();
                                    return;
                                }

                                setData({
                                    ...data, popupTriggers: [...popupTriggers, {
                                        selector: '',
                                        player: playerList[0].value,
                                    }]
                                })
                            }}>
                            <i className={`dashicons dashicons-plus-alt2`}></i>
                            <span>{wp.i18n.__('Add New Trigger', 'radio-player')}</span>
                        </button>

                    </div>
                </div>
            </div>

            {/* Popup Header Content */}
            <div className="setting-field field-editor">
                <h4 className={`setting-field-label`}>
                    {wp.i18n.__('Popup Header Content', 'radio-player')}
                    {!isPro &&
                        <span className="radio-player-pro-icon">
                            <i className={`radio-player-icon icon-pro`}/>
                        </span>
                    }
                </h4>

                <div className="setting-field-content">
                    <p className={'description'}>{wp.i18n.__('Add any custom content to the popup header. You can use HTML tags.', 'radio-player')}</p>

                    <div
                        className={`content-editor-wrap ${!isPro ? 'pro-disabled' : ''}`}
                         onClick={() => {
                             if (!isPro) {
                                 showProModal(wp.i18n.__('Upgrade to PRO to use the popup player.', 'radio-player'));
                                 return;
                             }
                         }}
                    >

                    <textarea
                        className={`content-editor ${!isPro ? 'disabled pro-disabled' : ''}`}
                        disabled={!isPro}
                        value={popupHeaderContent}
                        id={'header-content-editor'}
                        onChange={(e) => {
                            setData(data => ({...data, popupHeaderContent: e.target.value}))
                        }}
                    />

                    </div>

                </div>
            </div>

            {/* Popup Footer Content */}
            <div className="setting-field field-editor">
                <h4 className={`setting-field-label`}>
                    {wp.i18n.__('Popup Footer Content', 'radio-player')}
                    {!isPro &&
                        <span className="radio-player-pro-icon">
                            <i className={`radio-player-icon icon-pro`}/>
                        </span>
                    }
                </h4>

                <div className="setting-field-content">
                    <p className={'description'}>{wp.i18n.__('Add any custom content to the popup footer. You can use HTML tags.', 'radio-player')}</p>

                    <div className={`content-editor-wrap ${!isPro ? 'pro-disabled' : ''}`}
                         onClick={() => {
                             if (!isPro) {
                                 showProModal(wp.i18n.__('Upgrade to PRO to use the popup player.', 'radio-player'));
                                 return;
                             }
                         }}
                    >
                        <textarea
                            className={`content-editor ${!isPro ? 'disabled pro-disabled' : ''}`}
                            value={popupFooterContent}
                            id={'footer-content-editor'}
                            onChange={(e) => {
                                setData(data => ({...data, popupFooterContent: e.target.value}))
                            }}
                        />
                    </div>
                </div>
            </div>

        </div>
    )
}