import React, { useState, useMemo, useEffect } from 'react';
import PropTypes from 'prop-types';
import containerConnect from 'Framework/ComponentContainer';
import { setVisible } from '../../../Reducers/UI/Actions';
import { setLoadCode, loadConfiguration } from '../../../Reducers/Configurator/Actions';
import LoadConfiguration from '../../Components/LoadConfiguration';

export const LoadConfigurationContainer = ({
    LoadConfigurationComponent,
    close,
    setLoadCode,
    loadConfiguration,
    ...props
}) => {
    const [errorMessage, setErrorMessage] = useState();
    const onLoadClick = useMemo(
        () => async () => {
            try {
                await loadConfiguration();
            } catch (e) {
                setErrorMessage(e.message);
            }
        },
        [loadConfiguration]
    );

    // hide the message if the component is reopened or the user changed the code
    useEffect(() => setErrorMessage(''), [props.show, props.loadCode]);

    // hide the message if loading is in progress
    useEffect(() => {
        props.workInProgress && setErrorMessage('');
    }, [props.workInProgress]);

    return (
        <LoadConfigurationComponent
            {...props}
            onClose={close}
            onCodeChange={setLoadCode}
            onLoadClick={onLoadClick}
            errorMessage={errorMessage}
        />
    );
};
LoadConfigurationContainer.propTypes = {
    LoadConfigurationComponent: PropTypes.elementType.isRequired,
    close: PropTypes.func.isRequired,
    setLoadCode: PropTypes.func.isRequired,
    loadConfiguration: PropTypes.func.isRequired,
    show: PropTypes.bool.isRequired,
    loadCode: PropTypes.string.isRequired,
    workInProgress: PropTypes.bool.isRequired,
};

const mapStateToProps = ({ ui, configurator }) => ({
    Component: LoadConfigurationContainer,
    LoadConfigurationComponent: LoadConfiguration,
    show: !!ui.visibilityMap.loadConfiguration,
    workInProgress: !!ui.backgroundWorkMap.loadConfiguration,
    loadCode: configurator.loadCode || '',
});

const mapDispatchToProps = dispatch => ({
    close: () => dispatch(setVisible('loadConfiguration', false)),
    setLoadCode: code => dispatch(setLoadCode(code)),
    loadConfiguration: () => dispatch(loadConfiguration()),
});

export default containerConnect(mapStateToProps, mapDispatchToProps);
