import {useEffect, useState} from "@wordpress/element";
import {__} from "@wordpress/i18n";
import {required, validate} from "../../../../../../../../../../../validations";
import {handleError} from "../../../../../../../../../../helpers/notifications";
import DualInput from "../../../../../../../../../fields/dual-input";

export default function AddEdit({message, buttonLabel, autofocusOn, save, cancel, notifications}) {
    // Actions state
    const [saveButtonDisabled, setSaveButtonDisabled] = useState(false);
    // Data
    const [data, setData] = useState({
        input: '',
        output: '',
    });
    // Validation
    const dataErrors = {
        'input': useState(false),
        'output': useState(false)
    };

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

            switch (name) {
                case 'input':
                case 'output':
                    validations = [required];
                    break;
                default:
                    break;
            }
            const res = validate(value, validations);
            // Update field errors state
            if (name in errors) {
                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;
        }
    }

    useEffect(() => {
        // Setup message data
        setData(prevState => ({
            ...prevState,
            ...(message || {}),
            input: message?.input || '',
            output: message?.output || '',
        }));
    }, [message]);

    useEffect(() => {
        // Check for save button state
        if (data) {
            let hasErrors = false;
            for (const item of Object.keys(data)) {
                if (!validateField(item, data[item], {})) {
                    hasErrors = true;
                    break;
                }
            }
            setSaveButtonDisabled(hasErrors);
        } else {
            setSaveButtonDisabled(false);
        }
    }, [data]);

    /**
     * Save data
     */
    const saveData = () => {
        if (!saveButtonDisabled) {
            // Save data
            save(data);
            // Reset state
            setData({
                input: '',
                output: '',
            });
            return true;
        }
        return false;
    }

    return <tr className='lbaic-settings-a-ftds-table-body-in lbaic-settings-a-ftds-table-body-border'>
        <td colSpan='3' className='lbaic-settings-a-ftds-table-nested-body-item lbaic-settings-a-ftds-table-dual-input'>
            <div className='lbaic-settings-a-ftds-input'>
                <DualInput className='lbaic-settings-dual-input-has-children'
                           value1={data.input}
                           setValue1={(value) => setData(prevState => ({
                               ...prevState,
                               input: value
                           }))}
                           placeholder1={__("Question", 'limb-chatbot')}
                           validate1={(value) => validateField('input', value, dataErrors)}
                           errorMessage1={dataErrors['input'][0]}
                           value2={data.output}
                           setValue2={(value) => setData(prevState => ({
                               ...prevState,
                               output: value
                           }))}
                           placeholder2={__("Answer", 'limb-chatbot')}
                           validate2={(value) => validateField('output', value, dataErrors)}
                           errorMessage2={dataErrors['output'][0]}
                           autofocusOn={autofocusOn}
                           save={saveData} cancel={cancel}
                           notifications={notifications}
                           holderClassName='flex-2'/>
                <div className='lbaic-settings-a-ftds-input-action'>
                    <button
                        className={`lbaic-settings-button lbaic-settings-button-center lbaic-settings-button-h-34 lbaic-settings-button-minimal${saveButtonDisabled ? ' lbaic-settings-button-disabled' : ''}`}
                        onClick={saveData}>
                        <span className='lbaic-settings-button-label'>{buttonLabel}</span>
                    </button>
                </div>
            </div>
        </td>
    </tr>
}