import React from 'react';
import {
  SafeAreaView,
  Text,
  View,
  TouchableOpacity,
  StyleSheet,
  Image,
  TextInput,
  RefreshControl,
} from 'react-native';
var _ = require('lodash');
import { width, height } from '../../services/screen';
import Toast, { DURATION } from 'react-native-easy-toast';
import Modal, { ModalContent } from 'react-native-modals';
import { inject, observer } from "mobx-react"
import { observable, makeObservable } from 'mobx'
import { colors } from '../../assets/styles/colors-theme';
import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view';
import Rank from '../../components/rank';
import TitleBar from '../../components/titleBar';
import Icon from 'react-native-vector-icons/dist/MaterialCommunityIcons';
import FeatherIcon from 'react-native-vector-icons/dist/Feather';
import { ScrollView } from 'react-native-gesture-handler';

const ShoppingCart = inject("appStore")(observer(class ShoppingCart extends React.Component {


  allSelected = false;

  deleteAble = false;

  shippingPrice = 50;

  modifyQuantityVisable = false;

  productIndex = null;

  productQuantity = 0;
  constructor(props) {
    super(props);
    this.store = props.appStore;
    makeObservable(this, {
      allSelected: observable,

      deleteAble: observable,

      shippingPrice: observable,

      modifyQuantityVisable: observable,

      productIndex: observable,

      productQuantity: observable,
    })
  }

  priceHandler(price) {
    var priceInt = parseFloat(price).toFixed(2);
    return '$' + priceInt.toString();
  }

  totalPriceHandler() {
    var totalPrice = 0;
    this.store.shoppingCartList.map((items, index) => {
      totalPrice = totalPrice + items.price * items.buyCount;
    });
    console.log(totalPrice);
    return totalPrice;
  }
  async componentWillMount() {
    await this.checkAllSelected();
    this.store.getShoppingCart();
  }
  renderCheckBox() {
    if (!this.allSelected) {
      return (
        <Icon
          name="checkbox-blank-outline"
          color={colors.mainColor}
          style={{ marginTop: 2 }}
          size={18}
        />
      );
    } else {
      return (
        <Icon
          name="check-box-outline"
          color={colors.mainColor}
          style={{ marginTop: 2 }}
          size={18}
        />
      );
    }
  }

  allSelectClickAction() {
    if (this.allSelected) {
      this.store.favorite.map((items, index) => {
        this.store.favorite[index].selected = false;
      });
      this.allSelected = false;
      this.deleteAble = false;
    } else {
      this.store.favorite.map((items, index) => {
        this.store.favorite[index].selected = true;
      });
      this.allSelected = true;
      this.deleteAble = true;
    }
  }
  async addFavouriteAction(items) {
    if (
      (await this.store.favorite.findIndex(
        element => element.id == items.id,
      )) != -1
    ) {
      this.refs.toast.show('商品已存在我的清單');
    } else {
      console.log('addFavourite');
      this.store.addFavouritePost(_.cloneDeep(items), this);
    }
  }

  modifyQuantityAction() {
    if (parseInt(this.productQuantity) > 0) {
      if (
        parseInt(this.productQuantity) <
        this.store.shoppingCartList[this.productIndex].stock_quantity
      ) {
        //action
        this.store.modifyShoppingCart(
          this.productIndex,
          this,
          this.productQuantity,
        );
      } else {
        this.refs.toast.show(
          this.store.text.quantityCannotBeGreaterThanInventory,
        );
      }
    } else {
      this.refs.toast.show(this.store.text.quantityCannotBeZero);
    }
  }

  async checkAllSelected() {
    var allSelected = true;
    this.deleteAble = false;
    await this.store.favorite.map((items, index) => {
      if (!items.selected) {
        allSelected = false;
      } else {
        this.deleteAble = true;
      }
    });
    this.allSelected = allSelected;
  }

  clickItemCheckBoxAction(index) {
    this.store.favorite[index].selected = !this.store.favorite[index].selected;
    this.checkAllSelected();
  }

  deleteIconColorReturn() {
    if (this.deleteAble) {
      return colors.mainColor;
    } else {
      return colors.lineColor;
    }
  }

  async deleteAction() {
    var deleteIndex = [];
    await this.store.favorite.map((items, index) => {
      if (items.selected) {
        deleteIndex.push(index);
      }
    });
    const indexSet = new Set(deleteIndex);
    this.store.favorite = this.store.favorite.filter(
      (value, i) => !indexSet.has(i),
    );
    this.deleteAble = false;
  }

  allSelectOrAllUnselect() { }

  renderItemSelectBox(select, index) {
    if (select) {
      return (
        <TouchableOpacity
          onPress={() => {
            this.clickItemCheckBoxAction(index);
          }}>
          <Icon
            name="check-box-outline"
            color={colors.mainColor}
            style={{ marginTop: 2 }}
            size={18}
          />
        </TouchableOpacity>
      );
    } else {
      return (
        <TouchableOpacity
          onPress={() => {
            this.clickItemCheckBoxAction(index);
          }}>
          <Icon
            name="checkbox-blank-outline"
            color={colors.mainColor}
            style={{ marginTop: 2 }}
            size={18}
          />
        </TouchableOpacity>
      );
    }
  }

  async goToOrder() {
    this.store.orderList = [];
    await this.store.shoppingCartList.map(async (items, index) => {
      await this.store.orderList.push(_.cloneDeep(items));
    });

    if (this.store.orderList.length > 0) {
      this.props.navigation.navigate('Order');
    }
  }

  renderShoppingCartItems() {
    return this.store.shoppingCartList.map((items, index) => {
      return (
        <TouchableOpacity
          style={{ alignItems: 'center' }}
          onPress={() =>
            this.props.navigation.navigate('ProductsDetails', { data: items })
          }>
          <View
            style={{
              flexDirection: 'row',
              marginLeft: 20,
              marginTop: 20,
              marginBottom: 20,
            }}>
            <View style={{ flex: 0.05, marginTop: 5 }}>
              {/* {this.renderItemSelectBox(items.selected, index)} */}
            </View>
            <View
              style={{
                flexDirection: 'row',
                flex: 0.95,
                marginTop: 10,
                marginLeft: 5,
              }}>
              <Image
                style={{
                  height: 110,
                  width: 110,
                }}
                source={{
                  uri: items.images[0].src,
                }}
              />
              <View
                style={{
                  marginLeft: 20,
                  marginRight: 10,
                }}>
                <View style={{ height: 110, justifyContent: 'space-around' }}>
                  <Text numberOfLines={1} style={{ fontSize: 12, width: 180 }}>
                    {items.name}
                  </Text>
                  <Rank ranking={parseFloat(items.average_rating)} />
                  <Text
                    numberOfLines={1}
                    style={{
                      fontSize: 10,
                      marginTop: 10,
                      textDecorationLine: 'line-through',
                    }}>
                    {items.on_sale
                      ? this.store.text.originalPrice +
                      ' ' +
                      this.priceHandler(items.regular_price)
                      : ''}
                  </Text>
                  <Text
                    numberOfLines={1}
                    style={{
                      fontSize: 12,
                      color: items.on_sale ? 'red' : 'black',
                      fontWeight: 'bold',
                    }}>
                    {this.priceHandler(items.price)}
                  </Text>
                  <View
                    style={{
                      flexDirection: 'row',
                      marginTop: 10,
                      marginBottom: 10,
                    }}>
                    <Text style={{ fontSize: 10 }}>
                      {this.store.text.quantity + ':' + items.buyCount + ' '}
                    </Text>
                    <Text style={{ fontSize: 10, color: colors.lineColor }}>
                      {'| '}
                    </Text>
                    <Text style={{ fontSize: 10 }}>
                      {this.priceHandler(items.price * items.buyCount)}
                    </Text>
                  </View>
                  <View
                    style={{ height: 1, backgroundColor: colors.lineColor }}
                  />
                </View>

                <View
                  style={{
                    marginTop: 5,
                    flexDirection: 'row',
                    alignItems: 'center',
                  }}>
                  <TouchableOpacity
                    onPress={() => {
                      this.modifyQuantityVisable = true;
                      this.productIndex = index;
                      this.productQuantity = _.cloneDeep(items.buyCount);
                      //this.productCountInput.focus();
                    }}>
                    <Text style={{ fontSize: 10, color: colors.mainColor }}>
                      {this.store.text.changeQuantity}
                    </Text>
                  </TouchableOpacity>
                  <Text style={{ fontSize: 10, color: colors.lineColor }}>
                    {' | '}
                  </Text>
                  <TouchableOpacity
                    onPress={() => this.addFavouriteAction(items)}>
                    <Text style={{ fontSize: 10, color: colors.mainColor }}>
                      {this.store.text.addToFavourite}
                    </Text>
                  </TouchableOpacity>
                  <Text style={{ fontSize: 10, color: colors.lineColor }}>
                    {' | '}
                  </Text>
                  <TouchableOpacity
                    onPress={() => {
                      this.store.deleteShoppingCartItem(index, this);
                    }}>
                    <Icon name="delete" size={14} color={'gray'} />
                  </TouchableOpacity>
                </View>
              </View>
            </View>
          </View>
          <View
            style={{
              height: 1,
              width: width - 40,
              backgroundColor: colors.lineColor,
            }}
          />
        </TouchableOpacity>
      );
    });
  }

  render() {
    return (
      <SafeAreaView
        style={{
          flex: 1,
          backgroundColor: 'white',
        }}>
        <TitleBar self={this} showSearch={true} />
        <View
          style={{
            width: width,
            height: 30,
            borderColor: colors.lineColor,
            borderBottomWidth: 1,
            justifyContent: 'center',
            backgroundColor: 'white',
          }}>
          <Text style={{ color: colors.mainColor, marginLeft: 20, fontSize: 12 }}>
            {this.store.text.shoppingCartHave +
              ' ' +
              this.store.shoppingCartList.length +
              ' ' +
              this.store.text.products}
          </Text>
        </View>
        <KeyboardAwareScrollView
          refreshControl={
            <RefreshControl
              refreshing={this.store.loading}
              onRefresh={() => this.store.getShoppingCart()}
            />
          }>
          {this.store.shoppingCartList.length > 0 ? (
            <ScrollView>
              {this.renderShoppingCartItems()}
              <View
                style={{
                  width: width - 60,
                  margin: 20,
                  marginRight: 30,
                  alignItems: 'flex-end',
                }}>
                <View>
                  <Text style={{ fontSize: 12, marginTop: 5 }}>
                    {this.store.text.productPrice +
                      ': ' +
                      this.priceHandler(this.totalPriceHandler())}
                  </Text>
                  {/* <Text style={{fontSize: 12, marginTop: 5}}>
                    {this.store.text.shippingPrice +
                      ': ' +
                      this.priceHandler(this.shippingPrice)}
                  </Text> */}
                  <View
                    style={{
                      width: 120,
                      height: 1,
                      backgroundColor: colors.mainColor,
                      marginTop: 10,
                    }}
                  />
                  <Text
                    style={{ fontSize: 12, marginTop: 5, fontWeight: 'bold' }}>
                    {this.store.text.orderTotal +
                      ': ' +
                      this.priceHandler(this.totalPriceHandler())}
                  </Text>
                </View>
              </View>
              <View
                style={{
                  width: width,
                  justifyContent: 'center',
                  alignItems: 'center',
                  marginTop: 30,
                  marginBottom: 50,
                }}>
                <TouchableOpacity
                  onPress={() => {
                    this.goToOrder();
                  }}
                  style={{
                    height: 25,
                    width: 200,
                    justifyContent: 'center',
                    alignItems: 'center',
                    borderColor: colors.mainColor,
                    borderWidth: 1,
                    borderRadius: 5,
                  }}>
                  <Text style={{ color: colors.mainColor, fontSize: 12 }}>
                    {this.store.text.pay}
                  </Text>
                </TouchableOpacity>
              </View>
            </ScrollView>
          ) : (
            <View
              style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
              <Text>{this.store.text.shoppingcartEmpty}</Text>
            </View>
          )}
        </KeyboardAwareScrollView>
        <Modal
          visible={this.modifyQuantityVisable}
          width={0.5}
          height={0.2}
          onTouchOutside={() => {
            this.modifyQuantityVisable = false;
          }}
          swipeDirection={['up', 'down']} // can be string or an array
          swipeThreshold={200} // default 100
          onSwipeOut={event => {
            this.modifyQuantityVisable = false;
          }}>
          <ModalContent>
            <View
              style={{
                alignItems: 'center',
                justifyContent: 'center',
              }}>
              <View
                style={{
                  width: 80,
                  height: 30,
                  backgroundColor: colors.inputBgc,
                  justifyContent: 'center',
                  alignItems: 'center',
                  borderRadius: 10,
                }}>
                {this.productIndex != null ? (
                  <TextInput
                    style={{ fontSize: 15, color: colors.mainColor, paddingVertical: 0 }}

                    autoFocus={true}
                    value={'' + this.productQuantity}
                    keyboardType={'numeric'}
                    ref={input => {
                      this.productCountInput = input;
                    }}
                    onChangeText={text => (this.productQuantity = text)}
                  />
                ) : (
                  <View />
                )}
              </View>
              <TouchableOpacity
                style={{
                  marginTop: 20,
                  width: 80,
                  height: 30,
                  backgroundColor: colors.mainColor,
                  justifyContent: 'center',
                  alignItems: 'center',
                  borderRadius: 10,
                }}
                onPress={() => this.modifyQuantityAction()}>
                <Text style={{ color: 'white' }}>{this.store.text.sure}</Text>
              </TouchableOpacity>
            </View>
          </ModalContent>
        </Modal>

        <Toast
          ref="toast"
          style={{ backgroundColor: colors.mainColor }}
          position="bottom"
          positionValue={200}
          fadeInDuration={750}
          fadeOutDuration={2000}
          opacity={0.8}
          textStyle={{ color: 'white' }}
        />
      </SafeAreaView>
    );
  }
}))
const styles = StyleSheet.create({
  topBarButton: {
    justifyContent: 'center',
    alignItems: 'center',
    height: 25,
    borderColor: colors.lineColor,
    borderBottomWidth: 1,
    borderTopWidth: 1,
    flexDirection: 'row',
  },
  topBarText: {
    fontSize: 9,
  },
});
export default ShoppingCart