import React, { useEffect } from 'react';
import TitleBar from '../../components/titleBar';
import { colors } from '../../assets/styles/colors-theme';
import {
  SafeAreaView,
  Text,
  Image,
  ImageBackground,
  View,
  ScrollView,
  TouchableOpacity,
  RefreshControl,
  StyleSheet,
  BackHandler,
  AppState
} from 'react-native';
import { inject, observer } from 'mobx-react';
var _ = require('lodash');
import FastImage from 'react-native-fast-image'
import Toast, { DURATION } from 'react-native-easy-toast';
import CategoriesItems from '../../components/categoriesItems';
import { width, height } from '../../services/screen';
import Loading from '../../components/Loading';
import Ionicons from 'react-native-vector-icons/dist/Ionicons';
import { getStatusBarHeight } from 'react-native-status-bar-height';
import { observable } from 'mobx';
import { images } from '../../assets/images/imageIndex';
import Swiper from 'react-native-swiper';
import Icon from 'react-native-vector-icons/dist/MaterialCommunityIcons';
import Mostcheaplist from '../../components/mostcheaplist';
import YouMayLike from '../../components/youMayLikeItems';
import AsyncStorage from '@react-native-community/async-storage';
import Menu, {
  MenuProvider,
  MenuTrigger,
  MenuOptions,
  MenuOption,
  renderers,
} from 'react-native-popup-menu';
import YouMayLikeItems from '../../components/youMayLikeItems';
import { s, vs, ms } from 'react-native-size-matters';

const { SlideInMenu } = renderers;

@inject('appStore')
@observer
export default class Main extends React.Component {
  @observable
  catalogue = [];
  @observable
  subCatalogue = [{ name: '全部', id: '1234' }];
  @observable
  subCatalogueName = '全部';
  @observable
  catalogueImageUri = '';
  @observable
  productItems = [];
  @observable
  appState: AppState.currentState;
  @observable
  sortUpDown = false;
  constructor(props) {
    super(props);
    this.store = props.appStore;
    this.handleBackButtonClick = this.handleBackButtonClick.bind(this);
  }
  async componentDidMount() {

    AppState.addEventListener('change', this._handleAppStateChange);
    this._unsubscribe = this.props.navigation.addListener('focus', () => {
      this.store.getNotificationsMessage();
    });
    const value = await AsyncStorage.getItem('first');
    if (value !== null) {

    } else {
      this.props.navigation.navigate('Tutorial')
      AsyncStorage.setItem('first', 'true');

    }

  }
  _handleAppStateChange = (nextAppState) => {
    this.store.getNotificationsMessage();
    this.appState = nextAppState
  }


  async componentWillMount() {
    BackHandler.addEventListener('hardwareBackPress', this.handleBackButtonClick);
  }
  componentWillUnmount() {
    AppState.removeEventListener('change', this._handleAppStateChange);
    BackHandler.removeEventListener('hardwareBackPress', this.handleBackButtonClick);
    this._unsubscribe();
    this.store.getNotificationsMessage();

  }

  handleBackButtonClick() {
    this.sortUpDown = false;
    this.productItems = [];
    this.subCatalogue = [{ name: '全部', id: '1234' }];
    this.subCatalogueName = '全部';
    this.store.catalogueSelected = null;
    this.props.navigation.navigate('Main')
    return true;
  }

  async addFavouriteAction(item) {
    if (
      (await this.store.favorite.findIndex(element => element.id == item.id)) !=
      -1
    ) {
      this.refs.toast.show(this.store.text.alreadyExistsInMyList);
    } else {
      console.log('addFavourite');
      this.store.addFavouritePost(item, this);
    }
  }

  renderShoppingGroups() {
    return this.store.recommendShoppingGroup.map((items, index) => {
      return (
        <TouchableOpacity
          style={{
            width: width - 50,
            height: 60,
            backgroundColor: colors.shoppingGroupColor,
            borderRadius: 10,
            marginTop: 10,
            alignItems: 'center',
            flexDirection: 'row',
          }}
          onPress={() => {
            this.props.navigation.navigate('GroupDetails', {
              data: items,
              isRecommend: true,
            });
          }}>
          <View style={{ flex: 0.6, justifyContent: 'center' }}>
            <Text style={[styles.shoppingGroupText, { marginLeft: 20 }]}>
              {items.name}
            </Text>
          </View>
          <View style={{ flex: 0.3, alignItems: 'center', flexDirection: 'row' }}>
            {/* <Icon name="account" size={17} />
            <Text style={[styles.shoppingGroupText, { marginLeft: 5 }]}>
              {4 + '/' + 20}
            </Text> */}
          </View>
          <View
            style={{ flex: 0.1, alignItems: 'center', justifyContent: 'center' }}>
            <Icon name="chevron-right" size={25} />
          </View>
        </TouchableOpacity>
      );
    });
  }

  sortProduct() {
    var newArray = [...this.productItems];
    if (this.sortUpDown) {
      this.productItems = newArray.sort((a, b) =>
        a.price < b.price ? 1 : b.price < a.price ? -1 : 0,
      );
    } else {
      this.productItems = newArray.sort((a, b) =>
        a.price > b.price ? 1 : b.price > a.price ? -1 : 0,
      );
    }
  }

  renderCatalogueFilter() {
    if (this.store.catalogueSelected != null) {
      var productItem = [];
      var matrix = [];
      var newProductItem = [];
      var count = 0;
      // productItem = this.store.allProducts.filter(
      //   items => items.categories[0].name == this.store.catalogueSelected,
      // );
      productItem = this.productItems;
      productItem.map((items, index) => {
        count += 1;
        matrix.push(items);
        if (count % 2 == 0) {
          newProductItem.push(matrix);
          matrix = [];
          console.log(matrix);
        }
      });
      if (matrix.length > 0) {
        newProductItem.push(matrix);
        matrix = [];
      }

      console.log(newProductItem);

      return newProductItem.map((items, index) => {
        return (
          <View style={{ marginRight: 30, marginLeft: 30, flexDirection: 'row' }}>
            {items.map((item, index) => {
              return (
                <View
                  style={{
                    flex: 0.5,
                    alignItems: 'center',
                    justifyContent: 'center',
                  }}>
                  <CategoriesItems
                    data={item}
                    navigation={this.props.navigation}
                    showFav={true}
                    addfav={() => {
                      this.addFavouriteAction(item);
                    }}
                    onPress={() => {
                      console.log(item);
                      var newData = _.cloneDeep(item);
                      newData.buyCount = 1;
                      this.store.addSingleItemToShoppingCart(
                        _.cloneDeep(newData),
                        this,
                      );
                    }}
                  />
                </View>
              );
            })}
          </View>
        );
      });
    }
  }

  renderYouMayLike() {
    if (this.store.youMayLikeList.length > 0) {
      return this.store.youMayLikeList.map((items, index) => {
        return (
          <YouMayLikeItems
            data={items}
            index={index}
            navigation={this.props.navigation}
            onPress={() => {
              var newData = _.cloneDeep(items);
              newData.buyCount = 1;
              this.store.addSingleItemToShoppingCart(
                _.cloneDeep(newData),
                this,
              );
            }}
          />
        );
      });
    } else {
      return <View />;
    }
  }

  renderList() {
    if (this.store.topSale != null) {
      return this.store.topSale.map((items, index) => {
        return (
          <Mostcheaplist
            data={items}
            index={index}
            navigation={this.props.navigation}
            onPress={() => {
              var newData = _.cloneDeep(items);
              newData.buyCount = 1;
              this.store.addSingleItemToShoppingCart(
                _.cloneDeep(newData),
                this,
              );
            }}
          />
        );
      });
    } else {
      return <View />;
    }
  }

  addSubCatalogue(item) {
    if (item.subCat.length > 1) {
      item.subCat.map((items, index) => {
        this.subCatalogue.push(items);
      });
      console.log(this.subCatalogue);
    }
  }

  renderCatalogue() {
    return this.store.allCategories.map((items, index) => {
      var showImage = false;
      if (items.hasOwnProperty('imgURL')) {
        showImage = true;
      }
      return (
        <TouchableOpacity
          onPress={() => {
            this.sortUpDown = false;
            console.log(this.sortUpDown);
            this.store.getcategoriesProducts(items.id, this);
            //this.addSubCatalogue(items);
            this.store.catalogueSelected = items.name;
            if (items.hasOwnProperty('imgURL')) {
              this.catalogueImageUri = '';
            } else {
              this.catalogueImageUri = items.images[0].src;
            }
          }}
          style={{
            justifyContent: 'center',
            margin: 5,
            borderRadius: 10,
            width: s(90),
            height: s(90),
            backgroundColor: colors.inputBgc,
            alignItems: 'center',
          }}>
          {showImage ? (
            <View style={{ justifyContent: 'center', alignItems: 'center' }}>
              <FastImage
                source={{ uri: items.imgURL }}
                style={{
                  width: s(90),
                  height: s(90),
                  borderRadius: 10,
                  alignItems: 'center',
                  justifyContent: 'flex-end',
                }}
                resizeMode="stretch"></FastImage>

              <View
                style={{
                  backgroundColor: 'rgba(0, 0, 0, 0.74)',
                 // width: s(50),
                  height: s(20),
                  marginBottom: 5,
                  borderRadius: 10,
                  justifyContent: 'center',
                  alignItems: 'center',
                  position: 'absolute',
                  bottom: 1,
                }}>
                <Text
                  style={{ color: 'white', fontWeight: 'bold', fontSize: s(14) ,marginHorizontal:10,}}>
                  {items.name}
                </Text>
              </View>
            </View>
          ) : (
              <View
                style={{
                  width: s(90),
                  height: s(90),
                  borderRadius: 10,
                  alignItems: 'center',
                  justifyContent: 'flex-end',
                  backgroundColor: 'gray',
                }}>
                <View
                  style={{
                    backgroundColor: 'rgba(0, 0, 0, 0.74)',
                    width: s(50),
                    height: s(20),
                    marginBottom: 10,
                    borderRadius: 10,
                    justifyContent: 'center',
                    alignItems: 'center',
                  }}>
                  <Text
                    style={{ color: 'white', fontWeight: 'bold', fontSize: s(14) }}>
                    {items.name}
                  </Text>
                </View>
              </View>
            )}
        </TouchableOpacity>
      );
    });
  }

  async productsSubfilter(id) {
    console.log(id);
    if (id == '1234') {
      this.productItems = [...this.store.allProducts];
      this.sortProduct();
    } else {
      var newData = await this.store.allProducts.filter(function (item) {
        return item.categories[0].id == id;
      });
      this.productItems = [...newData];
      this.sortProduct();
    }
  }

  renderShoppingGroup() {
    if (this.store.loginUserData == null || this.store.loginUserData.data.hasOwnProperty('shoppingGroup')) {
      return (
        <View />
      )
    } else {
      return (
        <View>
          <View
            style={{
              marginTop: 20,
              flexDirection: 'row',
              width: width,
              alignItems: 'center',
            }}>
            <Text
              style={{
                fontSize: 20,
                marginLeft: 25,
                fontWeight: 'bold',
              }}>
              {this.store.text.shoppingGroup +
                this.store.text.recommend}
            </Text>
          </View>
          <View style={{ width: width, alignItems: 'center' }}>
            {this.renderShoppingGroups()}
          </View>
        </View>
      )
    }
  }

  render() {
    return (
      <MenuProvider
        style={{
          flex: 1,
          backgroundColor: 'white',
        }}>
        <Loading loading={this.store.loading} />
        {this.store.catalogueSelected == null ? (
          <TitleBar self={this} showSearch={true} showBack={false} />
        ) : (
            <View style={styles.naviBar}>
              <View style={[styles.barAreaView]}>
                <TouchableOpacity
                  style={{
                    flex: 0.2,
                    justifyContent: 'center',
                    alignItems: 'center',
                  }}
                  onPress={() => {
                    this.sortUpDown = false;
                    this.productItems = [];
                    this.subCatalogue = [{ name: '全部', id: '1234' }];
                    this.subCatalogueName = '全部';
                    this.store.catalogueSelected = null;
                  }}>
                  <Ionicons name="ios-arrow-back" color={'black'} size={40} />
                </TouchableOpacity>
                <View
                  style={{
                    flex: 0.6,
                    justifyContent: 'center',
                  }}>
                  <Text style={{ fontSize: 22, fontWeight: '800' }}>
                    {this.store.catalogueSelected}
                  </Text>
                </View>
                <View
                  style={{
                    flex: 0.2,
                    flexDirection: 'row',
                    alignItems: 'center',
                  }}>
                  <TouchableOpacity onPress={() => { this.props.navigation.navigate('Search') }}>
                    <Icon name="magnify" size={28} />
                  </TouchableOpacity>
                  <TouchableOpacity style={{ marginLeft: 10 }} onPress={() => { this.props.navigation.navigate('ShoppingCart') }}>
                    <Icon name={'shopping-outline'} size={28} />
                    <View
                      style={{
                        justifyContent: 'center',
                        alignItems: 'center',
                        position: 'absolute',
                        right: -5,
                        bottom: -3,
                      }}>
                      <Icon name="circle" color={colors.mainColor} size={18} />
                      <Text
                        style={{
                          position: 'absolute',
                          top: 4,
                          fontSize: 8,
                          color: 'white',
                        }}>
                        {this.store.shoppingCartList.length}
                      </Text>
                    </View>
                  </TouchableOpacity>
                </View>
              </View>
            </View>
          )}

        <ScrollView
          // contentContainerStyle={{flex: 1, justifyContent: 'center'}}
          style={{ flex: 1 }}
        // refreshControl={
        //   <RefreshControl
        //     refreshing={this.store.loading}
        //     onRefresh={() => this.store.getAllProductFromStart(this)}
        //   />
        // }
        >
          {this.store.catalogueSelected == null ? (
            <View>
              <View
                style={{
                  width: width,
                  justifyContent: 'center',
                  alignItems: 'center',
                  marginTop: 10,
                }}>

                <Swiper dotStyle={{ marginTop: 25 }} activeDotStyle={{ marginTop: 25 }} activeDotColor={colors.mainColor} autoplay={true} style={{ height: s(210), alignItems: 'center' }}>
                  {this.store.banners.map((items, index) => {
                    return (
                      <TouchableOpacity
                        onPress={() => {
                          if (items.hasOwnProperty('tags')) {
                            this.store.SearchTag(items.tags, this);
                            this.store.catalogueSelected = items.tags;
                          }
                        }}
                        style={{
                          justifyContent: 'center',
                          alignItems: 'center',
                        }}>
                        <FastImage
                          source={{ uri: items.imgURL }}
                          style={{
                            width: width,
                            height: s(170),
                            // marginLeft: 10,
                            //  marginRight: 10,
                            // borderRadius: 20,
                          }}
                          resizeMode="contain"
                        />
                      </TouchableOpacity>
                    );
                  })}
                </Swiper>
                <View
                  style={{
                    flexDirection: 'row',
                    width: width,
                    alignItems: 'center',
                    // marginTop: 10,
                  }}>
                  <Text
                    style={{
                      fontSize: 20,
                      marginLeft: 25,
                      fontWeight: 'bold',
                    }}>
                    {this.store.text.categories}
                  </Text>
                </View>

                <ScrollView horizontal={true}>
                  <View
                    style={{
                      flexDirection: 'row',
                      margin: 25,
                    }}>
                    {this.renderCatalogue()}
                  </View>
                </ScrollView>
                <View
                  style={{
                    width: width,
                    justifyContent: 'center',
                    alignItems: 'center',
                    marginTop: 10,
                  }}>
                  <Swiper dotStyle={{ marginTop: 25 }} activeDotStyle={{ marginTop: 25 }} activeDotColor={colors.mainColor} autoplay={true} style={{ height: s(210), alignItems: 'center' }}>
                    {this.store.news.map((items, index) => {
                      return (
                        <TouchableOpacity
                          onPress={() => { this.props.navigation.navigate('News', { data: items }) }}
                          style={{
                            justifyContent: 'center',
                            alignItems: 'center',
                          }}>
                          <FastImage
                            source={{ uri: items.imageURL }}
                            style={{
                              width: width,
                              height: s(170),
                              // marginLeft: 10,
                              //  marginRight: 10,
                              // borderRadius: 20,
                            }}
                            resizeMode="contain"
                          />
                        </TouchableOpacity>
                      );
                    })}
                  </Swiper>
                </View>
              </View>

              {/* {this.renderShoppingGroup()} */}
            </View>
          ) : (
              <View style={{ marginBottom: 10 }}>
                <View
                  style={{
                    marginTop: 10,
                    marginLeft: 40,
                    marginRight: 30,
                    width: width - 60,
                    flexDirection: 'row',
                    marginBottom: 10,
                  }}>
                  {/* <TouchableOpacity
                  style={{
                    flexDirection: 'row',
                    flex: 0.4,
                    alignItems: 'center',
                  }}
                  onPress={() => {
                    this.sortUpDown = false;
                    this.productItems = [];
                    this.subCatalogue = [{name: '全部', id: '1234'}];
                    this.subCatalogueName = '全部';
                    this.store.catalogueSelected = null;
                    console.log(this.sortUpDown);
                  }}>
                  <Image
                    source={{uri: this.catalogueImageUri}}
                    style={{height: 50, width: 50}}
                    resizeMode="contain"
                  />
                  <Text
                    style={{
                      color: colors.textColor,
                      fontWeight: '800',
                      marginLeft: 10,
                      fontSize: 15,
                    }}>
                    {this.store.catalogueSelected}
                  </Text>
                </TouchableOpacity> */}
                  {/* <View
                  style={{
                    flex: 0.3,
                    flexDirection: 'row',
                    alignItems: 'center',
                  }}>
                  <Menu
                    name="subcat"
                    renderer={SlideInMenu}
                    onSelect={value => {
                
                      this.subCatalogueName = value.name;
                      this.productsSubfilter(value.id);
                    }}>
                    <MenuTrigger style={{flexDirection: 'row'}}>
                      <View
                        style={{
                          alignItems: 'center',
                          justifyContent: 'center',
                          flexDirection: 'row',
                        }}>
                   
                        <Text
                          style={{
                            color: colors.textColor,
                            marginLeft: 5,
                            fontWeight: '800',
                          }}>
                          {'分類:'}
                        </Text>
                        <Text
                          style={{
                            color: colors.textColor,
                            marginLeft: 5,
                            fontWeight: '800',
                          }}>
                          {this.subCatalogueName}
                        </Text>
                      </View>
                    </MenuTrigger>
                    <MenuOptions
                      customStyles={{
                        optionText: {
                          margin: 5,
                          color: 'white',
                          fontSize: 20,
                        },
                        optionWrapper: {
                          backgroundColor: colors.mainColor,
                          alignItems: 'center',
                        },
                      }}>
                      <ScrollView style={{maxHeight: 300}}>
                        {this.subCatalogue.map((obj, i) => {
                          return <MenuOption value={obj} text={obj.name} />;
                        })}
                      </ScrollView>
                    </MenuOptions>
                  </Menu>
                </View> */}
                  <TouchableOpacity
                    style={{
                      flexDirection: 'row',

                      alignItems: 'center',
                      justifyContent: 'flex-end',
                      marginRight: 5,
                    }}
                    onPress={() => {
                      this.sortUpDown = !this.sortUpDown;
                      console.log(this.sortUpDown);
                      this.sortProduct();
                    }}>
                    <Text
                      style={{
                        fontWeight: '800',
                        fontSize: 10,
                      }}>
                      {this.store.text.sortby}
                    </Text>
                    <View
                      style={{
                        height: 15,
                        width: 15,
                        borderRadius: 15,
                        backgroundColor: colors.mainColor,
                        justifyContent: 'center',
                        alignItems: 'center',
                        marginLeft: 5,
                      }}>
                      <Icon
                        name={this.sortUpDown ? 'arrow-up' : 'arrow-down'}
                        color={'white'}
                      />
                    </View>
                    <Text
                      style={{
                        fontWeight: '800',
                        fontSize: 10,
                        marginLeft: 5,
                      }}>
                      {this.store.text.price}
                    </Text>
                  </TouchableOpacity>
                  {/* <View style={{flex: 0.5}}></View> */}
                </View>

                {this.renderCatalogueFilter()}
              </View>
            )}
        </ScrollView>
        <Toast
          ref="toast"
          style={{ backgroundColor: colors.mainColor }}
          position="bottom"
          positionValue={200}
          fadeInDuration={750}
          fadeOutDuration={2000}
          opacity={0.8}
          textStyle={{ color: 'white' }}
        />
      </MenuProvider>
    );
  }
}
const styles = StyleSheet.flatten({
  shoppingGroupText: {
    fontWeight: '800',
    fontSize: 15,
  },
  naviBar: {
    width,
    height: Platform.OS === 'ios' ? 70 : 75,
    backgroundColor: 'white',
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    marginTop: Platform.OS === 'ios' ? 0 : getStatusBarHeight(),
  },
  barAreaView: {
    flex: 1,
    marginRight: 20,
    marginLeft: 20,
    marginTop: Platform.OS === 'ios' ? -5 : 15,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
  },
});
