import React from 'react';
import {
  SafeAreaView,
  Text,
  View,
  TouchableOpacity,
  StyleSheet,
  Image,
} from 'react-native';
var _ = require('lodash');
import { width, height } from '../../services/screen';
import { inject, observer } from "mobx-react"
import { observable, makeObservable } from 'mobx'
import { colors } from '../../assets/styles/colors-theme';
import Rank from '../../components/rank';
import TitleBar from '../../components/titleBar';
import Toast, { DURATION } from 'react-native-easy-toast';
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 Favorite = inject("appStore")(observer(class Favorite extends React.Component {
  allSelected = false;
  deleteAble = false;
  constructor(props) {
    super(props);
    this.store = props.appStore;
    makeObservable(this, {
      allSelected: observable,
      deleteAble: observable,
    })
  }

  priceHandler(price) {
    var priceInt = parseFloat(price).toFixed(2);
    return '$' + priceInt.toString();
  }
  async componentWillMount() {
    this.store.getFavourite();
    // await this.checkAllSelected();
  }
  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}
        />
      );
    }
  }

  async addShoppingCartSingleItem(item) {
    var data = [];
    data.push(_.cloneDeep(item));
    item.buyCount = 1;
    this.store.addShoppingCart(data);
  }

  async addShoppingCart() {
    var cartdata = [];
    var originData = [];
    await this.store.favorite.map(async (items, index) => {
      // if (items.selected) {
      //   await data.push(_.cloneDeep(items));
      //   items.buyCount = 1;
      //   this.store.favorite[index].selected = false;
      // }
      if (items.selected) {
        var itemIndex = await this.store.shoppingCartList.findIndex(
          element => element.id === items.id,
        );
        var newData = _.cloneDeep(items);
        if (itemIndex != -1) {
          newData.buyCount =
            parseInt(newData.buyCount) +
            parseInt(this.store.shoppingCartList[itemIndex].buyCount);
          console.log(newData.buyCount);
        }

        var data = {
          product_id: items.id,
          qty: newData.buyCount,
          status: 1,
        };

        originData.push(newData);
        cartdata.push(data);

        items.buyCount = 1;
        this.store.favorite[index].selected = false;
      }
    });
    this.deleteAble = false;
    this.store.addShoppingCart(cartdata, this, originData);
  }

  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 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 = [];
    var deleteId = [];
    await this.store.favorite.map((items, index) => {
      if (items.selected) {
        deleteIndex.push(index);
        deleteId.push(items.id);
      }
    });

    await this.store.deleteFavourite(deleteIndex, deleteId, this);
  }

  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.favorite.map(async (items, index) => {
      if (items.selected) {
        await this.store.orderList.push(_.cloneDeep(items));
        items.buyCount = 1;
        this.store.favorite[index].selected = false;
      }
    });
    this.deleteAble = false;
    console.log(this.store.orderList);
    if (this.store.orderList.length > 0) {
      this.props.navigation.navigate('Order');
    }
  }

  renderFavorite() {
    return this.store.favorite.map((items, index) => {
      return (
        <View
          style={{ alignItems: 'center' }}
          onPress={() => {
            this.navigationAction();
          }}>
          <View
            style={{
              flexDirection: 'row',
              marginLeft: 20,
              marginTop: 20,
              marginBottom: 20,
            }}>
            <View style={{ flex: 0.05, marginTop: 5 }}>
              {this.renderItemSelectBox(items.selected, index)}
            </View>
            <TouchableOpacity
              style={{
                flexDirection: 'row',
                flex: 0.95,
                marginTop: 10,
                marginLeft: 5,
              }}
              onPress={() =>
                this.props.navigation.navigate('ProductsDetails', { data: items })
              }>
              {items.images.length > 0 ? (
                <Image
                  style={{
                    height: 110,
                    width: 110,
                  }}
                  source={{
                    uri: items.images[0].src,
                  }}
                />
              ) : (
                <View />
              )}

              <View
                style={{
                  marginLeft: 20,
                  marginRight: 10,
                  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 }}>
                  <View style={{ flexDirection: 'row' }}>
                    <TouchableOpacity
                      onPress={() => {
                        this.store.favorite[index].buyCount -= 1;
                      }}
                      style={{
                        height: 15,
                        width: 15,
                        backgroundColor: colors.mainColor,
                        alignItems: 'center',
                        justifyContent: 'center',
                      }}>
                      <Text style={{ color: 'white', fontSize: 14 }}>-</Text>
                      {/* <Icon name = 'remove' color = 'white'/> */}
                    </TouchableOpacity>
                    <View
                      style={{
                        width: 45,
                        height: 15,
                        borderColor: colors.lineColor,
                        borderRadius: 3,
                        borderWidth: 1,
                        marginLeft: 3,
                        marginRight: 3,
                        alignItems: 'center',
                        justifyContent: 'center',
                      }}>
                      <Text style={{ fontSize: 10 }}>{items.buyCount}</Text>
                    </View>
                    <TouchableOpacity
                      onPress={() => {
                        this.store.favorite[index].buyCount += 1;
                      }}
                      style={{
                        height: 15,
                        width: 15,
                        backgroundColor: colors.mainColor,
                        alignItems: 'center',
                        justifyContent: 'center',
                      }}>
                      <Text style={{ color: 'white', fontSize: 14 }}>+</Text>
                      {/* <Icon name = 'remove' color = 'white'/> */}
                    </TouchableOpacity>
                  </View>
                  <TouchableOpacity
                    onPress={() => {
                      //this.addShoppingCartSingleItem(items);
                      this.store.addSingleItemToShoppingCart(
                        _.cloneDeep(items),
                        this,
                      );
                    }}>
                    <FeatherIcon
                      color={colors.mainColor}
                      name="shopping-cart"
                      style={{ marginLeft: 10 }}
                      size={15}
                    />
                  </TouchableOpacity>
                </View>
              </View>
            </TouchableOpacity>
          </View>
          <View
            style={{
              height: 1,
              width: width - 40,
              backgroundColor: colors.lineColor,
            }}
          />
        </View>
      );
    });
  }

  render() {
    return (
      <SafeAreaView
        style={{
          flex: 1,
          backgroundColor: 'white'
        }}>
        <TitleBar self={this} showSearch={true} />
        <View
          style={{
            width: width,
            flexDirection: 'row',
            justifyContent: 'space-between',
          }}>
          <TouchableOpacity
            style={[styles.topBarButton, { flex: 0.2 }]}
            onPress={() => this.allSelectClickAction()}>
            {this.renderCheckBox()}
            <Text style={[styles.topBarText]}>{this.store.text.selectAll}</Text>
          </TouchableOpacity>
          <TouchableOpacity
            disabled={!this.deleteAble}
            style={[styles.topBarButton, { flex: 0.2, borderLeftWidth: 1 }]}
            onPress={() => {
              this.deleteAction();
            }}>
            <Icon
              name="delete"
              style={{ marginTop: 2 }}
              size={18}
              color={this.deleteIconColorReturn()}
            />
            <Text
              style={{
                color: this.deleteAble ? 'black' : colors.lineColor,
                fontSize: 9,
              }}>
              {this.store.text.remove}
            </Text>
          </TouchableOpacity>
          <TouchableOpacity
            disabled={!this.deleteAble}
            onPress={() => {
              this.addShoppingCart();
            }}
            style={[styles.topBarButton, { flex: 0.3, borderLeftWidth: 1 }]}>
            <FeatherIcon
              color={colors.mainColor}
              name="shopping-cart"
              style={{ marginRight: 5 }}
              size={12}
            />
            <Text style={[styles.topBarText]}>{this.store.text.addToShoppingCart}</Text>
          </TouchableOpacity>
          <TouchableOpacity
            onPress={() => {
              this.goToOrder();
            }}
            style={[styles.topBarButton, { flex: 0.3, borderLeftWidth: 1 }]}>
            <Icon
              color={colors.mainColor}
              name="credit-card"
              style={{ marginRight: 5, marginTop: 2 }}
              size={17}
            />
            <Text style={[styles.topBarText]}>{this.store.text.buy}</Text>
          </TouchableOpacity>
        </View>
        <ScrollView>{this.renderFavorite()}</ScrollView>
        <Toast
          ref="toast"
          style={{ backgroundColor: colors.mainColor }}
          position="bottom"
          positionValue={100}
          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 Favorite