import React from 'react';
import {
  SafeAreaView,
  Text,
  View,
  TouchableOpacity,
  StyleSheet,
  Image,
  TextInput,
  BackHandler,
} from 'react-native';
var _ = require('lodash');
import Toast, { DURATION } from 'react-native-easy-toast';
import { width, height } from '../../services/screen';
import { inject, observer } from 'mobx-react';
import { s, vs, ms } from 'react-native-size-matters';
import { colors } from '../../assets/styles/colors-theme';
import Rank from '../../components/rank';
import TitleBar from '../../components/titleBar';
import CategoriesItems from '../../components/categoriesItems';
import { observable } from 'mobx';
import { images } from '../../assets/images/imageIndex';
import Icon from 'react-native-vector-icons/dist/Ionicons';
import FeatherIcon from 'react-native-vector-icons/dist/Feather';
import { ScrollView } from 'react-native-gesture-handler';
import { Input } from 'react-native-elements';
@inject('appStore')
@observer
export default class Search extends React.Component {
  @observable
  searchText = '';
  constructor(props) {
    super(props);
    this.store = props.appStore;
    this.handleBackButtonClick = this.handleBackButtonClick.bind(this);
  }

  async componentWillMount() {
    BackHandler.addEventListener('hardwareBackPress', this.handleBackButtonClick);
  }

  componentWillUnmount() {
    BackHandler.removeEventListener('hardwareBackPress', this.handleBackButtonClick);

  }
  handleBackButtonClick() {
    this.props.navigation.goBack()
    return true;
  }

  searchAction() {
    if (this.searchText !== '') {
      this.store.searchProductsAction(this.searchText);
    } else {
    }
  }

  renderSearchHistory() {
    if (this.store.searchHistory == null) {
    } else {
      return this.store.searchHistory.map((items, index) => {
        return (
          <TouchableOpacity
            onPress={() => {
              this.store.searchProductsAction(items);
              this.searchText = items;
            }}
            style={{
              flexDirection: 'row',
              marginLeft: 40,
              marginRight: 40,
              justifyContent: 'space-between',
              alignItems: 'center',
              marginTop: 10,
            }}>
            <View style={{ flexDirection: 'row', alignItems: 'center' }}>
              <Icon color={colors.mainColor} name="md-search" size={15} />
              <Text style={{ marginLeft: 4 }}>{items}</Text>
            </View>
            <Icon
              name="chevron-forward-sharp"
              color={colors.mainColor}
              size={20}
            />
          </TouchableOpacity>
        );
      });
    }
  }

  renderResult() {
    if (this.store.searchResult.length > 0) {
      return <ScrollView style={{ flex: 1, marginTop: 20 }}>{this.renderItems()}</ScrollView>;
    } else {
      return (
        <View style={{ flex: 1, marginTop: 20 }}>
          <View
            style={{
              flexDirection: 'row',
              width: width - 80,
              marginRight: 40,
              marginLeft: 40,
              alignItems: 'center',
              justifyContent: 'space-between',
            }}>
            <Text style={{ fontSize: 12 }}>{this.store.text.searchRecords}</Text>
            <TouchableOpacity onPress={() => this.store.removeSearchHistory()}>
              <Text style={{ fontSize: 12 }}>
                {'X ' + this.store.text.clearHistory}
              </Text>
            </TouchableOpacity>
          </View>
          <ScrollView style={{ flex: 1, marginTop: 10 }}>
            {this.renderSearchHistory()}
          </ScrollView>
        </View>
      );
    }
  }

  async addShoppingCart(item) {
    var itemIndex = await this.store.shoppingCartList.findIndex(
      element => element.id === item.id,
    );

    if (itemIndex != -1) {
      this.store.shoppingCartList[itemIndex].buyCount += 1;

      this.store.shoppingCartIds[
        await this.store.shoppingCartIds.findIndex(
          element => element.itemId === item.id,
        )
      ].qty += 1;
    } else {
      var data = {
        itemId: item.id,
        qty: 1,
      };
      item.buyCount = 1;
      this.store.shoppingCartList.push(item);
      this.store.shoppingCartIds.push(data);
    }

    this.store.addShoppingCart(this);
  }

  renderItems() {
    var matrix = [];
    var newSearchItems = [];
    var count = 0;
    var searchItemsCopy = [];
    searchItemsCopy = this.store.removeDuplicates(
      this.store.searchResult,
      it => it.id,
    );

    searchItemsCopy.map((items, index) => {
      count += 1;
      matrix.push(items);
      if (count % 2 == 0) {
        newSearchItems.push(matrix);
        matrix = [];
      }
    });
    if (matrix.length > 0) {
      newSearchItems.push(matrix);
      matrix = [];
    }

    return newSearchItems.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}
                  onPress={() => {
                    this.addShoppingCart(item);
                  }}
                  navigation={this.props.navigation}
                />
              </View>
            );
          })}
        </View>
      );
    });
  }

  render() {
    return (
      <SafeAreaView
        style={{
          flex: 1,
          backgroundColor: colors.bgc,
        }}>
        <TitleBar
          self={this}
          showSearch={false}
          showBack={true}
          title={this.store.text.search}
        />

        <View
          style={{
            marginTop: 50,
            justifyContent: 'center',
            alignItems: 'center',
          }}>
          <Text style={{ fontWeight: '800', fontSize: 25 }}>
            {this.store.text.searchTitle}
          </Text>
        </View>

        <View
          style={{
            width: width,
            marginTop: 20,
            justifyContent: 'center',
            alignItems: 'center',
          }}>
          {/* <Input
            placeholder={this.store.text.searchForYourFavoriteProducts}
            rightIcon={{type: 'font-awesome', name: 'search'}}
            containerStyle={{width: width - 60}}
            onChangeText={value => this.setState({comment: value})}
            returnKeyType={'done'}
            onSubmitEditing={event => {
              this.searchAction();
            }}
            value={this.searchText}
            onChangeText={text => (this.searchText = text)}
          /> */}
          <View style={{ width: width - 60, height: 40, flexDirection: 'row', borderBottomWidth: 1, }}>
            <TextInput
              underlineColorAndroid="rgba(0,0,0,0)"
              style={{
                flex: 0.8, fontSize: 17,
                marginBottom: Platform.OS === 'ios' ? 3 : 0,
                paddingVertical: 0,
                marginLeft: 15,
              }}
              placeholder={this.store.text.searchForYourFavoriteProducts}
              onChangeText={value => this.setState({ comment: value })}
              returnKeyType={'search'}
              onSubmitEditing={event => {
                this.searchAction();
              }}
              value={this.searchText}
              onChangeText={text => (this.searchText = text)} />
            <TouchableOpacity style={{ flex: 0.2, justifyContent: 'center', alignItems: 'center' }}
              onPress={() => { this.searchAction(); }}>
              <Icon name='search-outline' size={25} />
            </TouchableOpacity>
          </View>
        </View>

        {this.renderResult()}
        <Toast
          ref="toast"
          style={{ backgroundColor: colors.mainColor }}
          position="center"
          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,
  },
});
