import {useState, useEffect} from "@wordpress/element";
import {__, sprintf} from "@wordpress/i18n";
import Toggle from "../../../../../../fields/toggle";
import Radio from "../../../../../../fields/radio";
import Container from "../../../../containers/content/container";
import TabSettings from "../../../../../components/tab-settings";
import WPObjectsGroupsMultiSelect from "../../../../../../fields/specific-fields/wp-objects-groups-multi-select";
import Description from "../../../../../../sections/description";
import Dropdown from "../../../../../../fields/dropdown";
import Notice from "../../../../../../sections/notice";
import {APPEAR_AFTER} from "../settings/data";
import CustomDelay from "../settings/custom-delay";
import {validate} from "../../../../../../../../validations";

// Constants
const TAB_NAME = 'settings.chatbot.display';

export default function Display({notifications, setChatbotPreview}) {
    // Actions states
    const [showPublishNotice, setShowPublishNotice] = useState(false);
    const [isDataFetched, setIsDataFetched] = useState(false);
    const [showInFetched, setShowInFetched] = useState(false);
    const [hideInFetched, setHideInFetched] = useState(false);
    const [showAddNewAppearAfterOptionPopup, setShowAddNewAppearAfterOptionPopup] = useState(false);

    // Settings
    const settings = {
        'status': useState(0),
        'show_in': useState(['all']),
        'hide_in': useState([]),
        'show_in_side': useState('right'),
        'appear_after': useState(0),
    };

    // Errors
    const errors = {
        'show_in': useState(false),
        'hide_in': useState(false),
    };

    /**
     * Validate field
     *
     * @param {string} name Field name
     * @param {any} value Field value
     * @return {boolean}
     */
    const validateField = (name, value) => {
        try {
            let validations = [];

            switch (name) {
                default:
                    return true;
            }

            const res = validate(value, validations);
            // Update field errors state
            errors[name][1](!res.valid ? res.message : false);
            return res.valid;
        } catch (e) {
            return false;
        }
    };

    // Handle show_in and hide_in conditional logic
    useEffect(() => {
        const showInValue = settings['show_in'][0];
        const hasAllValue = showInValue?.includes('all');

        // If show_in doesn't have 'all', clear hide_in field
        if (!hasAllValue && showInValue?.length > 0) {
            settings['hide_in'][1]([]);
        }
    }, [settings['show_in'][0]]);

    // Determine if hide_in field should be shown
    const shouldShowHideIn = isDataFetched && settings['show_in'][0]?.includes('all');

    /**
     * Add custom delay
     *
     * @param {number} value Custom value
     */
    const addCustomDelay = (value) => {
        const customAppearAfter = JSON.parse(localStorage.getItem('lbaic.settings.chatbot.settings.appear_after') || '[]');
        if (APPEAR_AFTER.findIndex(item => item.value === value) === -1 && customAppearAfter.findIndex(item => item.value === value) === -1) {
            customAppearAfter.push({
                label: sprintf(__('%d sec', 'limb-chatbot'), value),
                value: value,
            });
            APPEAR_AFTER.push({
                label: sprintf(__('%d sec', 'limb-chatbot'), value),
                value: value,
            });
            localStorage.setItem('lbaic.settings.chatbot.settings.appear_after', JSON.stringify(customAppearAfter));
        }
        settings['appear_after'][1](value);
        setShowAddNewAppearAfterOptionPopup(false);
    };

    const onDbDataReady = (data) => {
        setShowPublishNotice(+data?.status !== 1);
    };

    const showContent = isDataFetched && showInFetched;

    return <>
        <TabSettings
            name={TAB_NAME}
            settings={settings}
            notifications={notifications}
            keysPrefix='lbaic.utilities.chatbot'
            contentLoading={!showContent}
            setChatbotPreview={setChatbotPreview}
            dataFetched={value => setIsDataFetched(value)}
            validateField={validateField}
            shouldUpdatePreviewData
            onDbDataReady={onDbDataReady}
        >
            <Container className="lbaic-settings-cb-d">
                {showPublishNotice && (
                    <>
                        <Notice
                            type="warning"
                            desc={__("Check the toggle below to publish your chatbot.", 'limb-chatbot')}
                        />
                        <div className="lbaic-settings-divider-gap-end"/>
                    </>
                )}
                <div className="lbaic-settings-column">
                    <div className="lbaic-settings-column-in">
                        <Toggle label={__("Publish the chatbot", 'limb-chatbot')}
                                isActive={+settings['status'][0] === 1}
                                onClick={() => settings['status'][1](prevState => +prevState !== 1 ? 1 : 0)}/>
                        <Description>{__("Make the chatbot visible to visitors on your website", 'limb-chatbot')}</Description>
                    </div>
                    <div className="lbaic-settings-column-in"/>
                </div>
                <div className="lbaic-settings-column">
                    <div className="lbaic-settings-column-in">
                        <WPObjectsGroupsMultiSelect
                            value={settings['show_in'][0]}
                            setValue={settings['show_in'][1]}
                            placeholder={__("Show in pages", 'limb-chatbot')}
                            errorMessage={errors['show_in'][0]}
                            validate={value => validateField('show_in', value)}
                            addNotification={notifications.set}
                            isDataReady={isDataFetched}
                            setFetched={setShowInFetched}
                        />
                        <Description>{__("Select the WordPress public locations where your chatbot will be shown", 'limb-chatbot')}</Description>
                    </div>
                    <div className="lbaic-settings-column-in">
                        {shouldShowHideIn && (
                            <>
                                <WPObjectsGroupsMultiSelect
                                    value={settings['hide_in'][0]}
                                    setValue={settings['hide_in'][1]}
                                    placeholder={__("Hide in pages", 'limb-chatbot')}
                                    errorMessage={errors['hide_in'][0]}
                                    validate={value => validateField('hide_in', value)}
                                    addNotification={notifications.set}
                                    showAllOption={false}
                                    isDataReady={isDataFetched}
                                    setFetched={setHideInFetched}
                                />
                                <Description>{__("Select locations where the chatbot will be hidden", 'limb-chatbot')}</Description>
                            </>
                        )}
                    </div>
                </div>
                <div className="lbaic-settings-column">
                    <div className="lbaic-settings-column-in">
                        <div className='lbaic-settings-cb-a-column-footer'>
                            <div className='lbaic-settings-cb-a-column-footer-in'>
                                <div className='lbaic-settings-cb-a-column-footer-item'>
                                    <Radio label={__("Show in the left bottom", 'limb-chatbot')}
                                           isChecked={settings['show_in_side'][0] === 'left'}
                                           setValue={() => settings['show_in_side'][1]('left')}/>
                                </div>
                                <div className='lbaic-settings-cb-a-column-footer-item'>
                                    <Radio label={__("Show in the right bottom", 'limb-chatbot')}
                                           isChecked={settings['show_in_side'][0] === 'right'}
                                           setValue={() => settings['show_in_side'][1]('right')}/>
                                </div>
                            </div>
                        </div>
                        <Description>{__("Control where the chatbot icon appears on your website", 'limb-chatbot')}</Description>
                    </div>
                    <div className="lbaic-settings-column-in">
                        <Dropdown value={settings['appear_after'][0]} setValue={settings['appear_after'][1]}
                                  options={APPEAR_AFTER} defaultIcon="schedule"
                                  addNew={() => setShowAddNewAppearAfterOptionPopup(true)}
                                  placeholder={__("Appear after", 'limb-chatbot')}/>
                        <Description>{__("Delay in seconds before the chatbot icon appears", 'limb-chatbot')}</Description>
                    </div>
                </div>
            </Container>
        </TabSettings>
        {showAddNewAppearAfterOptionPopup &&
            <CustomDelay setValue={addCustomDelay} close={() => setShowAddNewAppearAfterOptionPopup(false)}
                         notifications={notifications}/>}
    </>
}
