import React from 'react';
import TitleBar from '../../components/titleBar';
import { colors } from '../../assets/styles/colors-theme';
import {
  SafeAreaView,
  Text,
  Image,
  ImageBackground,
  View,
  ScrollView,
  TouchableOpacity,
  RefreshControl,
} from 'react-native';
import { inject, observer } from "mobx-react"
import { observable, makeObservable } from 'mobx'
var _ = require('lodash');
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 FastImage from 'react-native-fast-image';
import { images } from '../../assets/images/imageIndex';
import Swiper from 'react-native-swiper';
import Carousel, { Pagination } from 'react-native-snap-carousel';
import Icon from 'react-native-vector-icons/dist/MaterialCommunityIcons';
import Mostcheaplist from '../../components/mostcheaplist';
import YouMayLike from '../../components/youMayLikeItems';
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 productCatalogue = [
  { name: '酒精飲品', uri: images.productCatalogue.alcoholic },
  { name: '蔬菜', uri: images.productCatalogue.vegetables },
  { name: '水果', uri: images.productCatalogue.fruit },
  { name: '零食', uri: images.productCatalogue.sneck },
  { name: '凍肉', uri: images.productCatalogue.frozenmeat },
  { name: '飲品', uri: images.productCatalogue.drink },
  { name: '急凍食品', uri: images.productCatalogue.frozenfood },
  { name: '海鮮', uri: images.productCatalogue.seafood },
  { name: '麵食', uri: images.productCatalogue.pasta },
];



const { SlideInMenu } = renderers;

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

  catalogue = [];

  subCatalogue = [{ name: '全部', id: '1234' }];

  subCatalogueName = '全部';

  catalogueSelected = null;

  catalogueImageUri = '';

  productItems = [];

  sortUpDown = false;

  activeSlide = 0;


  constructor(props) {
    super(props);
    this.store = props.appStore;
    makeAutoObservable(this, {

      catalogue: observable,

      subCatalogue: observable,

      subCatalogueName: observable,

      catalogueSelected: observable,

      catalogueImageUr: observable,

      productItems: observable,

      sortUpDown: observable,

      activeSlide: observable,
    })
  }
  componentDidMount() {
    //this.store.searchByCategories('飲')
    // this.store.searchByTag('可口')
    // this.store.searchItems('gg')
  }

  get pagination() {
    return (
      <Pagination
        dotsLength={this.store.topBanners.length}
        activeDotIndex={this.activeSlide}
        containerStyle={{ backgroundColor: colors.bgc }}
        dotStyle={{
          width: 10,
          height: 10,
          borderRadius: 5,
          marginHorizontal: 8,
          backgroundColor: colors.mainColor,
        }}
        inactiveDotStyle={
          {
            // Define styles for inactive dots here
          }
        }
        inactiveDotOpacity={0.4}
        inactiveDotScale={0.6}
      />
    );
  }

  _renderItem({ item, index }) {
    return (
      <View>
        <Image
          resizeMode='contain'
          source={{ uri: item.img_url }}
          style={{ width: width - 20, height: 230, }}
        />
      </View>
    );
  }

  closeCategoriesItems() {
    this.sortUpDown = false;
    this.productItems = [];
    this.subCatalogue = [{ name: '全部', id: '1234' }];
    this.subCatalogueName = '全部';
    this.catalogueSelected = null;
    console.log(this.sortUpDown);
  }

  async componentWillMount() { }

  renderSaleProducts() {
    var matrix = [];
    var newnewProductItem = [];
    var count = 0;
    this.store.saleProduct.map((items, index) => {
      count += 1;
      matrix.push(items);
      if (count % 2 == 0) {
        newnewProductItem.push(matrix);
        matrix = [];
        console.log(matrix);
      }
    });
    if (matrix.length > 0) {
      newnewProductItem.push(matrix);
      matrix = [];
    }

    console.log(newnewProductItem);
    return newnewProductItem.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}
                  sale={true}
                  onPress={() => {
                    var newData = _.cloneDeep(item);
                    newData.buyCount = 1;
                    this.store.addSingleItemToShoppingCart(
                      _.cloneDeep(newData),
                      this,
                    );
                  }}
                />
              </View>
            );
          })}
        </View>
      );
    });
  }

  renderGroupBuyProduct() {
    var matrix = [];
    var newnewProductItem = [];
    var count = 0;
    this.store.groupBuyList.map((items, index) => {
      count += 1;
      matrix.push(items);
      if (count % 2 == 0) {
        newnewProductItem.push(matrix);
        matrix = [];
        console.log(matrix);
      }
    });
    if (matrix.length > 0) {
      newnewProductItem.push(matrix);
      matrix = [];
    }

    console.log(newnewProductItem);
    return newnewProductItem.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}
                  groupBuy={true}
                  onPress={() => {
                    var newData = _.cloneDeep(item);
                    newData.buyCount = 1;
                    this.store.addSingleItemToShoppingCart(
                      _.cloneDeep(newData),
                      this,
                    );
                  }}
                />
              </View>
            );
          })}
        </View>
      );
    });
  }

  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.catalogueSelected != null) {
      var productItem = [];
      var matrix = [];
      var newProductItem = [];
      var count = 0;
      // productItem = this.store.allProducts.filter(
      //   items => items.categories[0].name == this.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);

      // var catalogueRowItems = [];
      // for (var i = 0; i < 2; i++) {
      //   catalogueRowItems.push(newProductItem[i]);
      // }

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

      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}
                    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.categories.map((items, index) => {
      return (
        <View style={{ flexDirection: 'row', alignItems: 'center' }}>
          {items.map((item, itemIndex) => {
            console.log(item)
            var showImage = false;
            if (item.hasOwnProperty('images')) {
              showImage = true;
            }
            return (
              <TouchableOpacity
                onPress={() => {
                  this.sortUpDown = false;
                  console.log(this.sortUpDown);
                  this.store.getcategoriesProducts(item.id, this);
                  this.addSubCatalogue(item);
                  this.catalogueSelected = item.name;
                  if (!item.hasOwnProperty('images')) {
                    this.catalogueImageUri = '';
                  } else {
                    this.catalogueImageUri = item.images[0].src;
                  }
                }}
                style={{
                  justifyContent: 'center',
                  margin: 5,
                  borderRadius: 10,
                  width: s(70),
                  height: s(70),
                  backgroundColor: colors.catColor,
                  alignItems: 'center',
                }}>
                {item.hasOwnProperty('images') ? (
                  <Image
                    source={{ uri: item.images[0].src }}
                    style={{ width: 45, height: 45 }}
                    resizeMode="contain"
                  />
                ) : (
                  <View
                    style={{
                      width: 45,
                      height: 45,
                      backgroundColor: 'gray',
                    }}></View>
                )}

                <View style={{ height: 25 }}>
                  <Text
                    style={{
                      color: colors.textColor,
                      marginTop: 5,
                      fontSize: 12,
                      fontWeight: '800',
                    }}>
                    {item.name}
                  </Text>
                </View>
              </TouchableOpacity>
            );
          })}
        </View>
      );
    });
  }

  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();
    }
  }

  render() {
    return (
      <MenuProvider
        style={{
          flex: 1,
          backgroundColor: colors.bgc,
        }}>
        <Loading loading={this.store.loading} />
        <TitleBar self={this} showSearch={true} isMain={true} />
        <ScrollView
          // contentContainerStyle={{flex: 1, justifyContent: 'center'}}
          style={{ flex: 1 }}
        // refreshControl={
        //   <RefreshControl
        //     refreshing={this.store.loading}
        //     onRefresh={() => this.store.getAllProductFromStart(this)}
        //   />
        // }
        >
          {this.catalogueSelected == null ? (
            <View>
              <View
                style={{
                  width: width,
                  justifyContent: 'center',
                  alignItems: 'center',
                  marginTop: 10,
                }}>
                <View style={{ width: width }}>
                  <Text
                    style={{
                      fontSize: 17,
                      marginLeft: 30,
                      marginRight: 30,
                      fontWeight: 'bold',
                      color: colors.mainColor,
                    }}>
                    {this.store.text.news}
                  </Text>
                </View>

                {/* <Swiper
                  removeClippedSubviews={false}
                  style={{
                    height: s(150),
                    justifyContent: 'center',
                    alignItems: 'center',
                  }}
                  activeDotColor={colors.mainColor}>
                  {this.store.banners.map((items, index) => {
                    return (
                      <View
                        style={{
                          justifyContent: 'center',
                          alignItems: 'center',
                        }}>
                        <Image
                          source={{uri: items.image_url}}
                          style={{width: width, height: s(150)}}
                          resizeMode="contain"
                        />
                      </View>
                    );
                  })}
                </Swiper> */}
                <Carousel
                  data={this.store.topBanners}
                  renderItem={this._renderItem}
                  onSnapToItem={index => {
                    this.activeSlide = index;
                  }}
                  sliderWidth={width}
                  itemWidth={width - 20}


                />
                {this.pagination}
                <View
                  style={{
                    flexDirection: 'row',
                    width: width,
                    alignItems: 'center',
                  }}>
                  <Image
                    source={images.main.foodcat}
                    style={{ marginLeft: 20 }}
                  />
                  <Text
                    style={{
                      fontSize: 17,
                      marginLeft: 5,
                      fontWeight: 'bold',
                      color: colors.mainColor,
                    }}>
                    {this.store.text.categories}
                  </Text>
                </View>
                <View
                  style={{
                    marginTop: 5,
                    alignItems: 'center',
                  }}>
                  <View>{this.renderCatalogue()}</View>
                </View>
              </View>

              <View
                style={{
                  flexDirection: 'row',
                  marginTop: 20,
                  marginLeft: 20,
                  alignItems: 'center',
                }}>
                <Image source={images.main.youmaylike} />
                <View style={{ justifyContent: 'center', marginLeft: 5 }}>
                  <Text
                    style={{
                      fontSize: 17,
                      marginLeft: 5,
                      fontWeight: 'bold',
                      color: colors.mainColor,
                    }}>
                    {this.store.text.youMightLike}
                  </Text>
                  <Text
                    style={{
                      fontSize: 12,
                      color: colors.subTextColor,
                      fontWeight: '800',
                      marginLeft: 5,
                    }}>
                    {this.store.text.youMightLikeTitle}
                  </Text>
                </View>
              </View>
              <ScrollView horizontal={true} style={{ margin: 20 }}>
                {this.renderYouMayLike()}
              </ScrollView>
              <Swiper
                removeClippedSubviews={false}
                style={{
                  height: s(150),
                  justifyContent: 'center',
                  alignItems: 'center',
                }}
                activeDotColor={colors.mainColor}>
                {this.store.bottomBanners.map((items, index) => {
                  return (
                    <View
                      style={{
                        justifyContent: 'center',
                        alignItems: 'center',
                      }}>
                      <Image
                        source={{ uri: items.img_url }}
                        style={{ width: width - 40, height: s(150) }}
                        resizeMode="contain"
                      />
                    </View>
                  );
                })}
              </Swiper>
            </View>
          ) : (
            <View style={{ marginBottom: 10 }}>
              <View
                style={{
                  marginTop: 20,
                  marginLeft: 30,
                  marginRight: 30,
                  width: width - 60,
                  flexDirection: 'row',
                  marginBottom: 20,
                }}>
                <TouchableOpacity
                  style={{
                    flexDirection: 'row',
                    flex: 0.4,
                    alignItems: 'center',
                  }}
                  onPress={() => {
                    this.closeCategoriesItems()
                  }}>
                  {this.catalogueImageUri == '' ? (<View style={{ height: 50, width: 50 }} />) : (<Image
                    source={{ uri: this.catalogueImageUri }}
                    style={{ height: 50, width: 50 }}
                    resizeMode="contain"
                  />)}

                  <Text
                    style={{
                      color: colors.textColor,
                      fontWeight: '800',
                      marginLeft: 10,
                      fontSize: 15,
                    }}>
                    {this.catalogueSelected}
                  </Text>
                </TouchableOpacity>
                <View
                  style={{
                    flex: 0.3,
                    flexDirection: 'row',
                    alignItems: 'center',
                  }}>
                  <Menu
                    name="subcat"
                    renderer={SlideInMenu}
                    onSelect={value => {
                      //  this.areaADropDownListOnSelect(value);
                      // this.flatListRef.scrollToOffset({
                      //   animated: true,
                      //   offset: 0,
                      // });
                      this.subCatalogueName = value.name;
                      this.productsSubfilter(value.id);
                    }}>
                    <MenuTrigger style={{ flexDirection: 'row' }}>
                      <View
                        style={{
                          alignItems: 'center',
                          justifyContent: 'center',
                          flexDirection: 'row',
                        }}>
                        {/* <Icon
                          name="map-marker-alt"
                          color={colors.mainColor}
                          size={17}
                        /> */}
                        <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',
                    flex: 0.3,
                    alignItems: 'center',
                    justifyContent: 'flex-end',
                    marginRight: 5,
                  }}
                  onPress={() => {
                    this.sortUpDown = !this.sortUpDown;
                    console.log(this.sortUpDown);
                    this.sortProduct();
                  }}>
                  <Text
                    style={{
                      color: colors.textColor,
                      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={{
                      color: colors.textColor,
                      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>
    );
  }
}))
export default Main
