import React, {useState, useEffect} from 'react';
import style from './buttonToIssueOrder.module.sass';
import {connect} from 'react-redux';
import {toIssueOrder, goodsBasketDataUpdate} from "../../../actions/actionCreator";
import ModalToIssueOrderUnregisterUser
    from '../../modals/modalToIssueOrderUnregisterUser/modalToIssueOrderUnregisterUser';

const ButtonToIssueOrder = (props) => {
    const {token, responseStatus, basketData} = props;
    const [showModal, setStatusIsShowModal] = useState(false);
    const orderGoodsData = [];

    basketData.map(elem => {
        orderGoodsData.push({
            goodsId: elem.selectedGoodId,
            count: elem.count
        })
    });

    const toIssueOrderHandler = () => {
        if(!token) {
            setStatusIsShowModal(true);
        }else {
            props.toIssueOrder({
               orderGoodsData: orderGoodsData
            });
            props.updateBasketData([]);
        }
    };

    if(showModal) {
        return (
            <>
                <ModalToIssueOrderUnregisterUser
                    isOpen={showModal}
                    onRequestClose={() => setStatusIsShowModal(false)}
                    orderGoodsData={orderGoodsData}
                />
                <div className={style.mainContainer} onClick={toIssueOrderHandler}>
                    Оформить заказ
                </div>
            </>
        );
    }

    return(
        <div className={style.mainContainer} onClick={toIssueOrderHandler}>
            Оформить заказ
        </div>
    )
};

const mapStateToProps = state => {
    const {responseStatus} = state.orderReducers;
    const {token} = state.signUpReducers;
    const {basketData} = state.goodsBasketReducers;

    return {
        responseStatus, token, basketData
    }
};

const mapDispatchToProps = dispatch => ({
    toIssueOrder: orderData => dispatch(toIssueOrder(orderData)),
    updateBasketData: basketData => dispatch(goodsBasketDataUpdate(basketData))
});

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