import { Component, Fragment } from 'react';
import { withRouter } from 'react-router-dom';
import { compose } from 'redux';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import Search from './search';
import DeckList from './deck-list';
import Button from '../shared/buttons/button';
import ConfirmModal from '../shared/confirm-modal';
import { createOrder } from '../../redux/actions/order';
import OrderAllDecksMessage from './order-all-decks-message';
import { addAllDecksToCart } from '../../redux/actions/cart';

const allInOneDiscountPercent = parseInt(process.env.REACT_APP_ALL_IN_ONE_DISCOUNT_PERCENT || 30);

class Store extends Component {
  constructor(props) {
    super(props);
    this.state = {
      orderAllDecks: false,
      showConfirmModal: false,
      selectedDecks: props.decks
    };
  }

  handleConfirm = async () => {
    this.setState({ showConfirmModal: false });
    if (this.state.orderAllDecks) await this.props.addAllDecksToCart();
    const {
      payload: { id }
    } = await this.props.createOrder();
    this.props.history.push(`/orders/${id}`);
  };

  handleSearch = searchName => {
    this.setState({
      selectedDecks: this.props.decks.filter(deck => deck.name.includes(searchName))
    });
  };

  render() {
    const discountPrice =
      (this.props.decks.reduce((acc, deck) => acc + deck.price, 0) * allInOneDiscountPercent) / 100;

    return (
      <Fragment>
        <OrderAllDecksMessage
          discountPercent={allInOneDiscountPercent}
          discountPrice={discountPrice}
          handleOrderAllDecks={() => this.setState({ orderAllDecks: true, showConfirmModal: true })}
        />
        <Search handleSearch={this.handleSearch} />
        <DeckList decks={this.state.selectedDecks} className='mt-8' />
        {this.props.cart.length > 0 && (
          <div className='fixed bottom-0 left-0 flex w-full flex-wrap items-center justify-center gap-2 bg-black bg-opacity-50 p-1.5'>
            <Button
              color='green'
              colorWeight={400}
              content='خرید بسته‌های انتخاب شده'
              onClick={() => this.setState({ orderAllDecks: false, showConfirmModal: true })}
            />
            <Button
              color='green'
              colorWeight={400}
              content='خرید همه بسته‌ها'
              onClick={() => this.setState({ orderAllDecks: true, showConfirmModal: true })}
            />
          </div>
        )}
        <ConfirmModal
          showModal={this.state.showConfirmModal}
          content={
            <p>
              <span>آیا از خرید </span>
              <span className='font-medium'>
                {this.state.orderAllDecks ? 'همه بسته‌ها' : 'بسته‌های انتخاب شده'}
              </span>
              <span> مطمئن هستید؟</span>
            </p>
          }
          onConfirm={this.handleConfirm}
          onCancel={() => this.setState({ showConfirmModal: false })}
        />
      </Fragment>
    );
  }
}

Store.propTypes = {
  decks: PropTypes.array.isRequired,
  cart: PropTypes.array.isRequired,
  addAllDecksToCart: PropTypes.func.isRequired,
  createOrder: PropTypes.func.isRequired,
  history: PropTypes.object.isRequired
};

function mapStateToProps({ cart }) {
  return { cart };
}

export default compose(
  withRouter,
  connect(mapStateToProps, {
    addAllDecksToCart,
    createOrder
  })
)(Store);
