import React, {useState} from 'react';
import {units} from "../../../constants/units";
import style from "./buttonBuy.module.sass";
import {connect} from 'react-redux';
import ModalBasket from "../../modals/modalBasketGoods/modalBasketGoods";
import {goodsBasketDataUpdate} from "../../../actions/actionCreator";

const ButtonBuy = (props) => {
    const {simpleGoodsData, changedPrice, changedValueAttributes, basketData} = props;
    const [showModal, setStatusModal] = useState(false);

    const buyButtonHandler = (e) => {
        const simpleGoodParams = {
            count: 1,
            price: changedPrice
        };
        let indexGoods = null;

        simpleGoodsData.GoodsAttributes.map(elem => {
            if(elem.valueAttribute == changedValueAttributes) {
                simpleGoodParams.volume = elem.valueAttribute + units[elem.nameAttribute];
                simpleGoodParams.mainPicture = elem.imgUrlArray[0];
                simpleGoodParams.selectedGoodId = elem.id;
            }
        });
        basketData.forEach((elem, index) => {
            if(elem.id == simpleGoodsData.id && elem.volume == simpleGoodParams.volume) {
                indexGoods = index;
            }
        });
        if(indexGoods || indexGoods === 0) {
            simpleGoodParams.count = basketData[indexGoods].count + 1;
            const insertGoodsData
                = Object.assign({}, simpleGoodsData, simpleGoodParams);

            basketData.splice(indexGoods, 1, insertGoodsData);
        }else {
            const insertGoodsData
                = Object.assign({}, simpleGoodsData, simpleGoodParams);

            basketData.push( insertGoodsData );
        }

        props.updateBasketData(basketData);
        setStatusModal(true)
    };

    const closeModal = () => {
      setStatusModal(false);
    };

        return(
            <>
                <ModalBasket
                    isOpen={showModal}
                    onRequestClose={closeModal}
                />
                <div className={style.button} onClick={buyButtonHandler}>
                    Купить
                </div>
            </>
        );
};

const mapStateToProps = state => {
    const {basketData} = state.goodsBasketReducers;

    return {
        basketData
    }
};
const mapDispatchToProps = dispatch => ({
    updateBasketData: (basketData) => dispatch(goodsBasketDataUpdate(basketData))
});

export default connect(mapStateToProps, mapDispatchToProps)(ButtonBuy);