import React from 'react'
import { withStyles } from '@material-ui/core/styles'
import { connect } from 'react-redux'
import { ShoppingBasketOutlined, Send, WarningRounded } from '@material-ui/icons/'
import {
  IconButton, ButtonBase, TextField, Grid, Button, CircularProgress,
} from '@material-ui/core/'
import axios from 'axios'
import ApiLink from '../components/ApiLink'
import master from '../images/master.png'
import rocket from '../images/rocket.png'
import nogod from '../images/nogod.png'
import visa from '../images/visa.png'
import bkash2 from '../images/bkash2.png'

const styles = {
  wrapper: {
    padding: 10,
    background: '#e8edf161',
  },
  paymentSlider: {
    margin: 10,
    padding: 10,
    background: 'white',
    borderRadius: 10,
  },
  pdtListItem: {
    display: 'flex',
    padding: 5,
    background: '#fff',
    borderRadius: 10,
    marginBottom: 13,
    boxShadow: '0px 0px 5px 0px rgba(157,171,209,.4)',
    '& > div': {
      width: '100%',
    },
  },
  pdtImg: {
    maxWidth: 70,
    maxHeight: 70,
    borderRadius: 8,
    marginRight: 5,
  },
  cartDel: {
    float: 'right',
    padding: 2,
    width: 30,
    height: 30,
    fontSize: 18,
  },
  paymentLogo: {
    background: '#fff',
    display: 'inline-flex',
    flexDirection: 'column',
    justifyContent: 'center',
    padding: 6,
    margin: 8,
    borderRadius: 10,
    boxShadow: '0px 0px 5px 0px rgba(157,171,209,.4)',
    alignItems: 'center',
    '& > img': {
      margin: 'auto',
      height: 25,
    },
    '& > small': {
      marginTop: 3,
      whiteSpace: 'pre',
    },
  },
  itemActive: {
    border: '3px solid #a6a6ff',
  },
}

function Orders(props) {
  // eslint-disable-next-line no-unused-expressions
  !props.auth && props.history.push('/')

  const login = localStorage.getItem('_log') != null ? JSON.parse(atob(localStorage.getItem('_log'))) : {}
  const token = localStorage.getItem('_token') != null ? JSON.parse(atob(localStorage.getItem('_token'))) : {}
  console.log(props.settings);
  const [slider, setSlider] = React.useState(0)
  const [adress, setAdress] = React.useState(token.adress)
  const [prefer, setPrefer] = React.useState('')
  const [bkashNum, setBkashNum] = React.useState('')
  const [tran, setTran] = React.useState('')
  const [refferal, setRefferal] = React.useState('')
  const [mobile, setMobile] = React.useState(login.mob)
  const [isLoading, setLoading] = React.useState(false)

  const classes = props.classes
  let total = 0
  let totalItem = 0
  props.cart.map(item => {
    total += item.price * item.quan
    totalItem += item.quan
    return true
  })

  function sendOrder(e) {
    e.preventDefault()
    if (mobile >= 1111111111 && bkashNum >= 1111111111) {
      if (!isLoading) {
        setLoading(true)
        let adressFlag = false
        if (adress !== token.adress) {
          adressFlag = true
          token.adress = adress
          localStorage.setItem('_token', btoa(JSON.stringify(token)))
        }

        const params = new URLSearchParams()
        params.append('adress', adress)
        params.append('adressFlag', adressFlag)
        params.append('prefer', prefer)
        params.append('bkashNum', bkashNum)
        params.append('paymentMethod', 'bKash')
        params.append('mobile', mobile)
        params.append('ownMobile', login.mob)
        params.append('tran', tran)
        params.append('total', total)
        params.append('totalItem', totalItem)
        params.append('ship', props.settings.ship_dhk)
        params.append('refferal', refferal)
        params.append('cart', JSON.stringify(props.cart))
        axios.post(ApiLink.cartOrder, params)
          .then(r => {
            console.log(r.data.success);
          })
          .catch(() => {

          })
        console.table(adress, prefer, bkashNum, tran, mobile);
      }
    }
  }
  return (
    <>
      <div className={classes.wrapper}>
        <div>
          <div style={{ overflowX: 'scroll', display: 'flex' }}>
            <ButtonBase onClick={() => setSlider(0)} className={`${classes.paymentLogo} ${slider === 0 && (classes.itemActive)}`}>
              <img src={bkash2} alt="bKash card mali-mart" />
              <small>bKash</small>
            </ButtonBase>
            <ButtonBase onClick={() => setSlider(1)} className={`${classes.paymentLogo} ${slider === 1 && (classes.itemActive)}`}>
              <img src={master} alt="Master card mali-mart" />
              <small>Master</small>
            </ButtonBase>
            <ButtonBase onClick={() => setSlider(2)} className={`${classes.paymentLogo} ${slider === 2 && (classes.itemActive)}`}>
              <img src={rocket} alt="Rocket card mali-mart" />
              <small>Rocket</small>
            </ButtonBase>
            <ButtonBase onClick={() => setSlider(3)} className={`${classes.paymentLogo} ${slider === 3 && (classes.itemActive)}`}>
              <img src={nogod} alt="Nogod card mali-mart" />
              <small>Nogod</small>
            </ButtonBase>
            <ButtonBase onClick={() => setSlider(4)} className={`${classes.paymentLogo} ${slider === 4 && (classes.itemActive)}`}>
              <img src={visa} alt="Visa card mali-mart" />
              <small>Visa</small>
            </ButtonBase>
          </div>
          <div className={classes.paymentSlider}>
            {slider === 0 && (
              <div>
                <div className="success_msg">
                  <WarningRounded />
                  <div>
                    Pay in our bKash Number
                    &nbsp;
                    <b>{props.settings.number}</b>
                    &nbsp;
                    and give the number of bKash and transaction Id (TrxId) below.
                  </div>
                </div>
                <br />
                <form onSubmit={sendOrder}>
                  <Grid
                    container
                    direction="row"
                    spacing={3}
                  >
                    <Grid item md={8} sm={11} xs={11}>
                      <TextField
                        id="adress"
                        label="Delivery Adress..."
                        value={adress}
                        onChange={e => setAdress(e.target.value)}
                        margin="dense"
                        variant="outlined"
                        multiline
                        rows={2}
                        fullWidth
                        required
                      />
                    </Grid>
                    <Grid item md={4} sm={11} xs={11}>
                      <TextField
                        id="prefer"
                        label="Color / Size / Other Preference"
                        value={prefer}
                        onChange={e => setPrefer(e.target.value)}
                        margin="dense"
                        variant="outlined"
                        multiline
                        rows={2}
                        fullWidth
                        required={false}
                      />
                    </Grid>
                  </Grid>


                  <TextField
                    id="personal_mob"
                    type="number"
                    className="inputField"
                    helperText="Give your contact number"
                    label="Your Mobile..."
                    value={mobile}
                    onChange={e => setMobile(e.target.value)}
                    margin="dense"
                    variant="outlined"
                    required
                  />
                  <TextField
                    id="bkash_num"
                    type="number"
                    className="inputField"
                    label="bKash Number..."
                    helperText="Payment bKash number"
                    value={bkashNum}
                    onChange={e => setBkashNum(e.target.value)}
                    margin="dense"
                    variant="outlined"
                    required
                  />
                  <TextField
                    id="cus_tran"
                    className="inputField"
                    label="Transaction ID"
                    helperText="Transaction ID (TrxId)"
                    value={tran}
                    onChange={e => setTran(e.target.value)}
                    margin="dense"
                    variant="outlined"
                    required
                  />
                  <TextField
                    id="refferal"
                    className="inputField"
                    label="Refferal Code (optional)"
                    helperText="Have any reffaral code for discount ?"
                    value={refferal}
                    onChange={e => setRefferal(e.target.value)}
                    margin="dense"
                    variant="outlined"
                  />

                  <Button id="order-btn" type="submit" variant="contained" color="primary">
                    <span id="order-btn-txt"> Send Order &nbsp;</span>
                    {!isLoading ? <Send id="snd" className="btn-icn" />
                      : <CircularProgress id="load" style={{ color: 'black' }} size={20} thickness={4} />}
                  </Button>
                  <div id="sm" className="d-non">
                    Order Complete Successfully ✔
                    <br />
                    {' '}
                    You Will get update about delivery process.Delivary Time 3-4 Working Days
                  </div>
                </form>
              </div>
            )}
            {slider === 1 && (
              <div>
                Mastercard Coming Soon....
                <br />
                Not Available Now.
              </div>
            )}
            {slider === 2 && (
              <div>
                Rocket Coming Soon....
                <br />
                Not Available Now.
              </div>
            )}
            {slider === 3 && (
              <div>
                Nogod Coming Soon....
                <br />
                Not Available Now.
              </div>
            )}
            {slider === 4 && (
              <div>
                Visa card Coming Soon....
                <br />
                Not Available Now.
              </div>
            )}
          </div>
        </div>
        <h3 style={{ display: 'flex' }}>
          {' '}
          <ShoppingBasketOutlined />
          {' '}
          &nbsp; Products in Cart
        </h3>
        <hr style={{ margin: '9px 0', border: '.5px solid #bfbfbf' }} />
        <h5>
          Total Item:
          {' '}
          {totalItem}
        </h5>
        <h5>
          Total Amount:
          {' '}
          {total}
        </h5>
        {props.cart.map((pdt) => (
          <div key={pdt.id} className={classes.pdtListItem}>
            <img className={classes.pdtImg} src={`${ApiLink.img_link}/mini/min${pdt.thumb}`} alt="cart thumbnail" />
            <div>
              <div>
                {pdt.name}
                <IconButton onClick={() => props.delFromCart(pdt.id)} className={classes.cartDel}>✖</IconButton>
              </div>
              <div style={{ color: 'gray' }}>
                -
                <i>{pdt.sub_cat}</i>
              </div>
              <div style={{ marginTop: 8 }}>
                Price:
                {' '}
                {pdt.price}
                {' '}
                x
                {' '}
                {pdt.quan}
                {' '}
                Pcs
              </div>
            </div>
          </div>
        ))}
      </div>
    </>
  )
}


function mapStateToProps(state) {
  return {
    auth: state.auth,
    settings: state.settings,
    cart: state.cart,
  }
}


function mapDispatchToProps(dispatch) {
  return {
    delFromCart: pdtId => dispatch({ type: 'delFromCart', payload: pdtId }),
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(withStyles(styles)(Orders));
