import React, { useState } from 'react';
import PropTypes from 'prop-types';

import CustomDialog from 'Shared/Components/CustomDialog';
import CustomDialogSelect from 'Shared/Components/CustomDialogSelect';

import MainButton from 'Shared/Components/MainButton';
import FastConfigurationRow from '../FastConfigurationRow';
import FastConfigurationSelect from '../FastConfigurationSelect';
import { T } from 'Framework/i18n';
import './Styles.scss';
import isArray from 'lodash/isArray';
import merge from 'lodash/merge';

const FastConfiguration = ({
    optionclassifications,
    options,
    FastConfigurationRow,
    FastConfigurationSelect,
    onOptionclassificationSelect,
    onOptionSelect,
    isLoading,
    languageSettings,
    channelSettings,
    PriceComponent,
    calculation,
    onDoneClick,
    show,
    onClose,
}) => {
    const [productPartSelected, setProductPartSelected] = useState({ index: 0, content: {} });
    const [isOptionsDialogOpen, setOptionsDialogOpen] = useState(false);

    const getStyles = index => {
        return {
            detailsDialog: {
                top: 'calc(103px + 50 * (' + index + 'px + 1px)',
                left: '40%',
                width: 10,
                height: 200,
                position: 'absolute',
            },
        };
    };

    const getSelectedOption = optionClassification => {
        return optionClassification.selectedoptions
            ? optionClassification.selectedoptions.length === 1
                ? optionClassification.selectedoptions[0]
                : optionClassification
            : undefined;
    };

    const getUpdatedOptions = () => {
        const optionClassification = productPartSelected;
        const updatedOptions = [];

        for (let option of options) {
            let uo = option;
            if (isArray(optionClassification.selectedoptions)) {
                for (let selectedOption of optionClassification.selectedoptions) {
                    if (selectedOption.identifier === option.identifier) {
                        uo = merge({}, option, selectedOption);
                    } else if (option.option_group && isArray(option.option_group.children)) {
                        for (let item of option.option_group.children) {
                            if (selectedOption.identifier === item.identifier) {
                                uo = merge({}, option, selectedOption);
                                break;
                            }
                        }
                    }
                }
            }
            updatedOptions.push(uo);
        }
        return updatedOptions;
    };

    const onFocus = optionClassification => {
        onOptionclassificationSelect(optionClassification, false);
    };

    const selectOptionAndCloseDialog = option => {
        onOptionSelect(option);
        closeOptionsDialog();
    };

    const closeOptionsDialog = () => {
        setOptionsDialogOpen(false);
    };

    const openOptionsDialog = (index, content) => {
        setOptionsDialogOpen(true);
        setProductPartSelected({ index, content });
    };

    const toggleOptionsDialog = (index, productPart = {}) => {
        isOptionsDialogOpen ? closeOptionsDialog() : openOptionsDialog(index, productPart);
    };

    const renderRows = () => {
        return optionclassifications.map((optionClassification, index) => {
            return (
                <FastConfigurationRow
                    key={'optionclassificationitem' + optionClassification.identifier}
                    optionclassification={optionClassification}
                >
                    <FastConfigurationSelect
                        {...{
                            optionClassification,
                            options,
                            onOptionclassificationSelect,
                            onOptionSelect,
                            isLoading,
                            languageSettings,
                            channelSettings,
                        }}
                        closeDialog={closeOptionsDialog}
                        getValue={getSelectedOption}
                        onFocus={onFocus}
                        rowIndex={index}
                        toggleDialog={toggleOptionsDialog}
                    />
                </FastConfigurationRow>
            );
        });
    };

    const renderHeader = () => {
        return null;
    };

    const renderFooter = () => {
        return (
            <div className="fastconfiguration-footer">
                <div className="fastconfiguration-price">
                    <PriceComponent {...{ calculation, title: T('price.label') }} />
                </div>
                <MainButton className={'fastconfiguration-done'} onClick={onDoneClick} variant="contained">
                    {T('fastconfiguration.toConfigurator')}
                </MainButton>
            </div>
        );
    };

    const renderComponent = () => {
        const { detailsDialog } = getStyles(productPartSelected.index);
        const selectedOption = getSelectedOption(productPartSelected.content);
        const updatedOptions = getUpdatedOptions();

        return (
            <CustomDialog
                open={show}
                onCancel={onClose}
                onClose={onClose}
                dialogTitle={T('fastConfiguration.dialogTitle')}
                className={'fastconfiguration-dialog'}
            >
                <div className="fastconfiguration">
                    {renderHeader()}

                    <div className="fastconfiguration-rows-wrapper">{renderRows()}</div>

                    {renderFooter()}
                </div>
                {isOptionsDialogOpen ? (
                    <div style={detailsDialog}>
                        <CustomDialogSelect
                            options={updatedOptions}
                            show={isOptionsDialogOpen}
                            isLoading={isLoading}
                            onSelectOption={selectOptionAndCloseDialog}
                            selectedOption={selectedOption}
                            selectedOptionProperty={'identifier'}
                        />
                    </div>
                ) : null}
            </CustomDialog>
        );
    };

    return renderComponent();
};

FastConfiguration.defaultProps = {
    options: [],
    optionclassifications: [],
    onOptionclassificationSelect: () => {},
    onOptionSelect: () => {},
    FastConfigurationRow,
    FastConfigurationSelect,
    calculation: {},
    onDoneClick: () => {},
};

FastConfiguration.propTypes = {
    options: PropTypes.array,
    optionclassifications: PropTypes.array,
    onOptionclassificationSelect: PropTypes.func,
    onClose: PropTypes.func,
    show: PropTypes.bool,
    onOptionSelect: PropTypes.func,
    FastConfigurationRow: PropTypes.oneOfType([PropTypes.element, PropTypes.func]),
    FastConfigurationSelect: PropTypes.oneOfType([PropTypes.element, PropTypes.func]),
    calculation: PropTypes.object,
    onDoneClick: PropTypes.func,
    PriceComponent: PropTypes.elementType,
    isLoading: PropTypes.bool,
    languageSettings: PropTypes.object,
    channelSettings: PropTypes.object,
};

export default FastConfiguration;
