import React from 'react';
import PropTypes from 'prop-types';
import { containerConnect } from 'Framework/ComponentContainer';
import BulkNames from '../Components/BulkNames';
import find from 'lodash/find';
import sumBy from 'lodash/sumBy';
import flatten from 'lodash/flatten';
import get from 'lodash/get';
import isEmpty from 'lodash/isEmpty';

class BulkNamesContainer extends React.Component {
    static propTypes = {
        textInputs: PropTypes.array,
        totalAmount: PropTypes.func,
        handleDelete: PropTypes.func,
        saveConfigurationBulkNames: PropTypes.func,
        handleText: PropTypes.func,
        handleChange: PropTypes.func,
        handleSave: PropTypes.func,
        onClose: PropTypes.func,
        addTextField: PropTypes.func,
        activeSizeVariant: PropTypes.object,
        selectedVariant: PropTypes.object,
        BulkNamesComponent: PropTypes.func,
    };
    initialState = {
        textInputs: [{ text: '', amount: 1 }],
    };
    state = this.initialState;

    componentDidMount() {
        const { selectedVariant, activeSizeVariant } = this.props;
        if (selectedVariant.sizes.length > 0) {
            const sizeVariant = find(selectedVariant.sizes, { identifier: activeSizeVariant.identifier });
            const bulkNamesSizes = sizeVariant.bulkNames;
            const bulkNamesInputs = Object.values(
                bulkNamesSizes.reduce((indexedNames, text) => {
                    const amount = get(indexedNames, `${text}.amount`, 0) + 1;
                    indexedNames = { ...indexedNames, [text]: { text, amount } };
                    return indexedNames;
                }, {})
            );
            if (bulkNamesSizes.length > 0) {
                this.setState({
                    textInputs: bulkNamesInputs,
                });
            }
        } else {
            const bulkNames = selectedVariant.bulkNames;
            const bulkNamesInputs = Object.values(
                bulkNames.reduce((indexedNames, text) => {
                    const amount = get(indexedNames, `${text}.amount`, 0) + 1;
                    indexedNames = { ...indexedNames, [text]: { text, amount } };
                    return indexedNames;
                }, {})
            );
            if (bulkNames.length > 0) {
                this.setState({ textInputs: bulkNamesInputs });
            }
        }
    }

    totalAmount = () => {
        const { textInputs } = this.state;
        let filledBulkNameInputs = [];
        for (const input of textInputs) {
            if (input.text !== '') {
                if (input.amount === 0) {
                    input.amount = 1;
                }
                filledBulkNameInputs.push(input);
            }
        }
        return sumBy(filledBulkNameInputs, 'amount');
    };

    saveBulkNamesConfiguration = () => {
        const { selectedVariant, activeSizeVariant, handleChange, handleSave, onClose } = this.props;
        const { textInputs } = this.state;

        const summedAmount = this.totalAmount();
        handleChange(summedAmount);

        const reformattedTextInputs = flatten(
            textInputs.map(input => {
                let inputs = [];
                if (input.text !== '') {
                    for (let i = 1; i <= input.amount; i++) {
                        inputs.push(input.text);
                    }
                }
                return inputs;
            })
        );

        if (selectedVariant.sizes.length > 0) {
            const sizeVariant = find(selectedVariant.sizes, { identifier: activeSizeVariant.identifier });
            handleSave(sizeVariant.identifier, reformattedTextInputs);
        } else {
            handleSave(selectedVariant.identifier, reformattedTextInputs);
        }
        onClose();
    };

    handleText = (text, i) => e => {
        const textInputs = [...this.state.textInputs];

        if (text === 'text') {
            textInputs[i].text = e.target.value;
        } else {
            textInputs[i].amount = e;
        }
        this.setState({ textInputs });
    };

    addTextField = e => {
        e.preventDefault();
        const textInputs = this.state.textInputs.concat({ text: '', amount: 1 });
        this.setState({ textInputs });
    };

    handleDelete = i => e => {
        e.preventDefault();
        let textInputs = [...this.state.textInputs.slice(0, i), ...this.state.textInputs.slice(i + 1)];
        this.setState({ textInputs });
    };
    render() {
        const { textInputs } = this.state;
        const { BulkNamesComponent, activeSizeVariant, ...props } = this.props;
        const size = !isEmpty(activeSizeVariant) && activeSizeVariant.size.split(' ').pop();
        return (
            <BulkNamesComponent
                handleDelete={this.handleDelete}
                addTextField={this.addTextField}
                textInputs={textInputs}
                handleText={this.handleText}
                saveConfigurationBulkNames={() => this.saveBulkNamesConfiguration()}
                totalAmount={this.totalAmount}
                size={size}
                activeSizeVariant={activeSizeVariant}
                {...props}
            />
        );
    }
}

const mapStateToProps = () => ({
    Component: BulkNamesContainer,
    BulkNamesComponent: BulkNames,
});

export default containerConnect(mapStateToProps);
