import containerConnect from 'Framework/ComponentContainer';
import InvalidConfigurationNotice from '../../Components/InvalidConfigurationNotice';
import { setVisible } from 'App/Reducers/UI/Actions';
import { getConfiguration } from '../../../Reducers/Configurator/Selectors';
import { getCached } from '../../../../Utils/Function/cached';
import { getConf } from 'App/configuration';

/**
 * Stores the mapped validation errors in cache to keep the same reference if the source has not changed
 * this makes possible to show up the dialog when it gets new list of errors.
 * @param configuratorState
 * @return {*}
 */
const getValidationErrors = configuratorState => {
    const { validation } = configuratorState;
    const { optionclassifications } = getConfiguration(configuratorState);
    return getCached(
        'getValidationErrors',
        validation,
        optionclassifications && optionclassifications.length
    ).use(() => {
        if (validation.code && validation.code === 'minimum_order_amount_error') {
            let errors = [];
            let itemTitle = '';
            validation.errors.forEach((error, index) => {
                itemTitle = error.itemTitle;
                errors.push({
                    message: 'minimumOrderAmountError',
                    key: index,
                    amounts: {
                        minAmount: error.minimumAmount,
                        selectedAmount: error.selectedAmount,
                    },
                });
            });

            return [
                {
                    title: itemTitle,
                    errors,
                },
            ];
        }
        const errors = validation?.validationErrors || validation?.errors || {};
        return !optionclassifications
            ? []
            : Object.entries(errors).map(([key, error]) => ({
                  title:
                      optionclassifications.find(({ identifier }) => identifier === key)?.title ||
                      error.componentTitle,
                  errors: error.errors,
                  key,
              }));
    });
};

const mapStateToProps = ({ configurator, ui }) => {
    const validationErrors = getValidationErrors(configurator);

    return {
        adminMode: getConf('adminMode'),
        Component: InvalidConfigurationNotice,
        validationErrors,
        show: !!ui.visibilityMap.validationResult,
    };
};

const mapDispatchToProps = dispatch => ({
    close: () => dispatch(setVisible('validationResult', false)),
    open: () => dispatch(setVisible('validationResult', true)),
});

export default containerConnect(mapStateToProps, mapDispatchToProps);
