import {useEffect, useState} from "@wordpress/element";
import {__} from "@wordpress/i18n";
import Input from "../../../../fields/input";
import {handleError} from "../../../../../helpers/notifications";
import {required, validate} from "../../../../../../validations";
import PopupContainer from "../../../../popups/container";

export default function CustomOption({setValue, title, type, label, close, notifications}) {
    // Tune data
    const settings = {
        'value': useState(''),
    };
    const errors = {
        'value': 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) {
                case 'value':
                    validations = [required];
                    break;
                default:
                    break;
            }
            const res = validate(value, validations);
            // Update field errors state
            errors[name][1](!res.valid ? res.message : false);

            return res.valid;
        } catch (e) {
            handleError(e, notifications.set, {
                title: __("Field validation failed.", 'limb-chatbot'),
                description: e.message ? __(e.message, 'limb-chatbot') : __("Something went wrong.", 'limb-chatbot'),
            });
            return false;
        }
    }

    /**
     * Run tuning
     */
    const save = () => {
        let hasError = false;
        for (const item of Object.keys(settings)) {
            if (!validateField(item, settings[item][0])) {
                hasError = true;
            }
        }
        if (!hasError) {
            setValue(+settings['value'][0]);
        }
    }

    /**
     * Handle keyboard interactions
     *
     * @param {KeyboardEvent} event
     */
    const handleKeyDown = (event) => {
        if (event.key === 'Enter') {
            event.preventDefault();
            save();
        } else if (event.key === 'Escape') {
            event.preventDefault();
            close();
        }
    }

    // Handle Escape key globally
    useEffect(() => {
        const handleKey = (e) => {
            if (e.key === 'Escape') {
                close();
            }
        }

        window.addEventListener('keydown', handleKey);
        return () => window.removeEventListener('keydown', handleKey);
    }, [close]);

    return (
        <PopupContainer
            title={title}
            description={__("Fill the following field", 'limb-chatbot')}
            close={close}
            footer={
                <>
                    <button className='lbaic-settings-button lbaic-settings-button-center lbaic-settings-button-h-40 lbaic-settings-button-primary'
                            onClick={save}>
                        <span className='lbaic-settings-button-label'>{__("Save", 'limb-chatbot')}</span>
                    </button>
                    <button className='lbaic-settings-button lbaic-settings-button-center lbaic-settings-button-h-40 lbaic-settings-button-secondary'
                            onClick={close}>
                        <span className='lbaic-settings-button-label'>{__("Cancel", 'limb-chatbot')}</span>
                    </button>
                </>
            }
        >
            <Input value={settings['value'][0]} setValue={settings['value'][1]}
                   type={type}
                   placeholder={label}
                   autofocus
                   validate={(value) => validateField('value', value)}
                   errorMessage={errors['value'][0]}
                   onKeyDown={handleKeyDown}/>
        </PopupContainer>
    );
}