import React, { useRef } from 'react';
import TitleBar from '../../components/titleBar';
import { colors } from '../../assets/styles/colors-theme';
import {
  SafeAreaView,
  Text,
  Image,
  View,
  ScrollView,
  TouchableOpacity,
  RefreshControl,
  FlatList,
  ActivityIndicator,
  TouchableHighlightBase
} from 'react-native';
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 { Col, Grid, Row } from "react-native-easy-grid";
import { inject, observer } from "mobx-react"
import { observable, makeObservable } 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 YouMayLikeItems from '../../components/youMayLikeItems';
import { s, vs, ms } from 'react-native-size-matters';
import SkeletonPlaceholder from "react-native-skeleton-placeholder";
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 fakedata = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }, { id: 5 }, { id: 6 }, { id: 7 }, { id: 8 }, { id: 9 }, { id: 10 },]

const Main = inject("appStore")(observer(class Main extends React.Component {
  onEndReachedCalledDuringMomentum = true
  catalogue = [];
  catalogueSelected = null;
  imageLoading = false;
  catalogueImageUri = '';
  productItems = [];
  constructor(props) {
    super(props);
    this.store = props.appStore;
    makeObservable(this, {
      imageLoading: observable,
      catalogue: observable,
      catalogueSelected: observable,
      catalogueImageUri: observable,
      productItems: observable,
      onEndReachedCalledDuringMomentum: observable,
    })
  }
  componentDidMount() {
    //this.store.searchByCategories('飲')
    // this.store.searchByTag('可口')
    // this.store.searchItems('gg')
  }

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


  renderFooter() {

    return (
      //Footer View with Loader
      <View style={{
        padding: 10,
        justifyContent: 'center',
        alignItems: 'center',
        flexDirection: 'row',
      }}>
        {this.store.footerLoading ? (
          <ActivityIndicator color={colors.mainColor} style={{ margin: 15 }} />
        ) : null}
      </View>
    );
  };


  onEndReachedHandler() {
    if (!this.store.footerLoading && !this.store.flatlistEnd && !this.onEndReachedCalledDuringMomentum) {
      this.store.getProductsByCategory(this.catalogueSelected.id, false)
      this.onEndReachedCalledDuringMomentum = true
    }
  }

  renderCategoryProducts() {
    if (this.catalogueSelected != null) {
      return (
        <View style={{ marginBottom: 40 }}>
          <FlatList
            columnWrapperStyle={{ justifyContent: 'space-between', marginVertical: 30, }}
            data={this.store.categoriesProducts}
            keyExtractor={item => item.id}
            onEndReached={() => this.onEndReachedHandler()}
            onMomentumScrollBegin={() => { this.onEndReachedCalledDuringMomentum = false; }}
            onEndReachedThreshold={0.1}
            horizontal={false}
            numColumns={2}
            ListFooterComponent={this.renderFooter()}
            renderItem={({ item, index }) => (
              <View style={{ alignItems: 'center', width: width / 2, }}>
                <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>
      )
    }

  }
  imagesOnload(loading) {
    this.imageLoading = loading
  }
  renderBanners() {
    if (this.store.banners.length > 0) {
      return (
        <Swiper
          removeClippedSubviews={false}
          style={{
            height: s(120),
            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 - 40, height: s(150) }}
                  resizeMode="contain"
                />
              </View>
            );
          })}
        </Swiper>
      )
    } else {
      return (
        <SkeletonPlaceholder>
          <View style={{ width: width - 40, height: s(150) }} />
        </SkeletonPlaceholder>
      )
    }
  }

  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 fakedata.map((items, index) => {
        return (
          <SkeletonPlaceholder>
            <View
              style={{ borderColor: colors.mainColor, borderWidth: 1, marginRight: 10 }}
            >
              <View
                style={{
                  margin: 10,
                  height: 180,
                }}>

                <View style={{ flex: 0.7 }}>

                  <View
                    style={{
                      height: 90,
                      width: 90,
                    }}
                  />

                  <View style={{ width: 12, width: 90 }}>

                  </View>
                </View>

                <View style={{ flex: 0.3 }}>
                  <View style={{ flex: 0.5 }}>
                    <View

                      style={{
                        height: 10,
                        width: 70

                      }}>

                    </View>
                    <View

                      style={{
                        height: 12,
                        width: 70,
                    marginTop: 5,

                      }}>

                    </View>
                  </View>
                  <View style={{ flex: 0.5, justifyContent: 'flex-end' }}>
                    <View
                      style={{
                        flexDirection: 'row',
                        backgroundColor: colors.mainColor,
                        height: 17,
                        width: 75,
                        alignItems: 'center',
                        justifyContent: 'center',
                        borderRadius: 5,
                      }}
                    >

                    </View>
                  </View>
                </View>
              </View>
            </View>
          </SkeletonPlaceholder>
        );
      })
    }
  }

  renderList() {
    if (this.store.topSale.length > 0) {
      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 (
        <SkeletonPlaceholder>
          <View
            style={{ borderColor: colors.lineColor, borderBottomWidth: 1 }}
            onPress={() => {
              this.navigationAction();
            }}>
            <View
              style={{
                flexDirection: 'row',
                marginLeft: 20,
                marginTop: 20,
                marginBottom: 20,
              }}>
              <View
                style={{
                  flexDirection: 'row',
                  flex: 0.85,
                  marginTop: 10,
                }}>
                <View
                  style={{
                    height: 110,
                    width: 110,
                  }}

                />
                <View style={{ marginLeft: 20, marginRight: 10 }}>
                  <View style={{ height: 12, width: 150 }}>

                  </View>
                  <View style={{ height: 12, width: 50, marginTop: 5 }}>

                  </View>

                  <View style={{ height: 12, width: 70, marginTop: 15 }}>

                  </View>
                  <View style={{ height: 12, width: 50, marginTop: 5 }}>

                  </View>
                  <View
                    style={{
                      flexDirection: 'row',
                      backgroundColor: colors.mainColor,
                      height: 17,
                      width: 75,
                      alignItems: 'center',
                      justifyContent: 'center',
                      borderRadius: 5,
                      position: 'absolute',
                      bottom: 0,
                    }}
                  >

                  </View>
                </View>
              </View>

            </View>
          </View>
        </SkeletonPlaceholder>
      )
    }
  }

  renderCatalogue() {
    if (this.store.categories.length > 0) {
      return (
        <FlatList
          columnWrapperStyle={{ marginVertical: 10, }}
          data={this.store.categories}
          keyExtractor={item => item.id}
          horizontal={false}
          numColumns={5}
          renderItem={({ item, index }) => (
            <TouchableOpacity
              onPress={() => {
                this.catalogueSelected = item;
                this.productItems = [];
                this.store.getProductsByCategory(item.id, true)
                if (item.image === null) {
                  this.catalogueImageUri = '';
                } else {
                  this.catalogueImageUri = item.image.src;
                }
              }}
              style={{
                justifyContent: 'center',
                width: s(70),
                height: s(80),
                alignItems: 'center',
              }}>
              {item.image !== null ? (
                <Image
                  source={{ uri: item.image?.src }}
                  style={{ width: 40, height: 40 }}
                  resizeMode="contain"
                />

              ) : (
                <Image
                  source={images.main.logo}
                  style={{ width: 40, height: 40 }}
                  resizeMode="contain"
                />
              )}

              <View style={{ height: 40 }}>
                <Text
                  style={{
                    color: colors.titleColor,
                    marginTop: 10,
                    fontSize: 12,
                  }}>
                  {item.name}
                </Text>
              </View>
            </TouchableOpacity>
          )}
        />
      );
    } else {

      return (
        <FlatList
          columnWrapperStyle={{ marginVertical: 10, }}
          data={fakedata}
          keyExtractor={item => item.id}
          horizontal={false}
          numColumns={5}
          renderItem={({ item, index }) => (
            <SkeletonPlaceholder>
              <View
                style={{
                  justifyContent: 'center',
                  width: s(70),
                  height: s(80),
                  alignItems: 'center',
                }}>
                <View
                  style={{ width: 40, height: 40 }}
                />
                <View style={{ height: 40, justifyContent: 'center' }}>
                  <View style={{ height: 10, width: 40, borderRadius: 4 }} />
                </View>
              </View>
            </SkeletonPlaceholder>
          )}
        />
      )
    }
  }

  render() {
    return (
      <SafeAreaView
        style={{
          flex: 1,
          backgroundColor: 'white',
        }}>
        <Loading loading={this.store.loading} />
        <TitleBar self={this} showSearch={true} />
        {this.catalogueSelected == null ? (
          <ScrollView
            style={{ flex: 1 }}
          >

            <View>{this.renderCatalogue()}</View>

            <View>
              <View
                style={{
                  width: width,
                  justifyContent: 'center',
                  alignItems: 'center',
                }}>
                {this.renderBanners()}
              </View>

              {this.store.groupBuyList.length > 0 ? (
                <View>
                  <View
                    style={{
                      width: width,
                      height: 10,
                      backgroundColor: colors.lineColor,
                      marginTop: 10,
                    }}
                  />
                  <View
                    style={{
                      flexDirection: 'row',
                      marginTop: 20,
                      marginLeft: 20,
                      alignItems: 'center',
                    }}>
                    <Icon name="bullhorn" color={colors.mainColor} size={35} />
                    <View style={{ justifyContent: 'center', marginLeft: 5 }}>
                      <Text style={{ color: colors.titleColor }}>
                        {this.store.text.groupbuy}
                      </Text>
                      <Text style={{ fontSize: 10 }}>
                        {this.store.text.groupbuytitle}
                      </Text>
                    </View>
                  </View>
                  {this.renderGroupBuyProduct()}
                </View>
              ) : (
                <View />
              )}

              {this.store.saleProduct.length > 0 ? (
                <View>
                  <View
                    style={{
                      width: width,
                      height: 10,
                      backgroundColor: colors.lineColor,
                      marginTop: 10,
                    }}
                  />
                  <View
                    style={{
                      flexDirection: 'row',
                      marginTop: 20,
                      marginLeft: 20,
                      alignItems: 'center',
                    }}>
                    <Icon name="timer" color={colors.mainColor} size={35} />
                    <View style={{ justifyContent: 'center', marginLeft: 5 }}>
                      <Text style={{ color: colors.titleColor }}>
                        {this.store.text.limitedTimeOffers}
                      </Text>
                      <Text style={{ fontSize: 10 }}>
                        {this.store.text.limitedTimetitle}
                      </Text>
                    </View>
                  </View>
                  {this.renderSaleProducts()}
                </View>
              ) : (
                <View />
              )}
              <View
                style={{
                  width: width,
                  height: 10,
                  backgroundColor: colors.lineColor,
                  marginTop: 10,
                }}
              />
              <View
                style={{
                  flexDirection: 'row',
                  marginTop: 20,
                  marginLeft: 20,
                  alignItems: 'center',
                }}>
                <Image source={images.main.mostcheapstar} />
                <View style={{ justifyContent: 'center', marginLeft: 5 }}>
                  <Text style={{ color: colors.titleColor }}>
                    {this.store.text.cheapestThisWeek}
                  </Text>
                  <Text style={{ fontSize: 10 }}>
                    {this.store.text.cheapestThisWeekTitle}
                  </Text>
                </View>
              </View>
              {this.renderList()}
              <View
                style={{
                  flexDirection: 'row',
                  marginTop: 20,
                  marginLeft: 20,
                  alignItems: 'center',
                }}>
                <Image source={images.main.youmaylike} />
                <View style={{ justifyContent: 'center', marginLeft: 5 }}>
                  <Text style={{ color: colors.titleColor }}>
                    {this.store.text.youMightLike}
                  </Text>
                  <Text style={{ fontSize: 10 }}>
                    {this.store.text.youMightLikeTitle}
                  </Text>
                </View>
              </View>
              <ScrollView horizontal={true} style={{ margin: 20 }}>
                {this.renderYouMayLike()}
              </ScrollView>
            </View>

          </ScrollView>
        ) : (
          <View style={{ flex: 1, marginBottom: 40 }}>
            <View
              style={{
                marginTop: 20,
                marginLeft: 30,
                marginRight: 30,
                width: width - 60,
                flexDirection: 'row',
                marginBottom: 20,
              }}>
              <TouchableOpacity
                style={{
                  flexDirection: 'row',
                  flex: 0.5,
                  alignItems: 'center',
                }}
                onPress={() => (this.catalogueSelected = null)}>

                <Image
                  source={{ uri: this.catalogueImageUri }}
                  style={{ height: 50, width: 50 }}
                  resizeMode="contain"
                />
                <Text
                  style={{
                    color: colors.titleColor,
                    marginLeft: 10,
                    fontSize: 15,
                  }}>
                  {this.catalogueSelected.name}
                </Text>
              </TouchableOpacity>
              <View style={{ flex: 0.5 }}></View>
            </View>

            {this.renderCategoryProducts()}
          </View>
        )}
        <Toast
          ref="toast"
          style={{ backgroundColor: colors.mainColor }}
          position="bottom"
          positionValue={200}
          fadeInDuration={750}
          fadeOutDuration={2000}
          opacity={0.8}
          textStyle={{ color: 'white' }}
        />
      </SafeAreaView>
    );
  }
}))
export default Main
