import React from 'react';
import {
  SafeAreaView,
  Text,
  View,
  TouchableOpacity,
  StyleSheet,
  Image,
  TextInput,
} from 'react-native';
var _ = require('lodash');
import { width, height } from '../../services/screen';
import { inject, observer } from "mobx-react"
import { observable, makeObservable } from 'mobx'
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 { 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';
const Search = inject("appStore")(observer(class Search extends React.Component {

  searchText = '';
  constructor(props) {
    super(props);
    this.store = props.appStore;

    makeObservable(this, {
      searchText: observable,
    })
  }

  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' }}>
              <Image source={images.search.smallGreenMagnifier} />
              <Text style={{ marginLeft: 4, color: colors.grayTextColor }}>
                {items}
              </Text>
            </View>
            <Icon name="ios-arrow-forward" color={colors.mainColor} size={20} />
          </TouchableOpacity>
        );
      });
    }
  }

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

  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}
                  navigation={this.props.navigation}
                />
              </View>
            );
          })}
        </View>
      );
    });
  }

  render() {
    return (
      <SafeAreaView
        style={{
          flex: 1,
          backgroundColor: 'white',
        }}>
        <TitleBar self={this} showSearch={false} />
        <View style={{ width: width, marginTop: 10, flexDirection: 'row' }}>
          <TouchableOpacity
            style={{
              marginLeft: 10,
              height: 40,
              width: 40,
              justifyContent: 'flex-start',
              alignItems: 'center',
            }}
            onPress={() => {
              this.store.searchResult = [];
              this.props.navigation.goBack();
            }}>
            <Icon name="ios-arrow-back" color={colors.mainColor} size={40} />
          </TouchableOpacity>
          <View
            style={{
              flexDirection: 'row',
              marginTop: 10,
            }}>
            <Image source={images.search.greenMagnifier} tintColor={'black'} />
            <View>
              <View
                style={{
                  width: s(270),
                  height: 22,
                  marginLeft: 5,
                  backgroundColor: 'white',
                  borderWidth: 1,
                  borderColor: colors.borderLineColor,
                  borderRadius: 5,
                  justifyContent: 'center',
                }}>
                <TextInput
                  returnKeyType={'done'}
                  onSubmitEditing={event => {
                    this.searchAction();
                  }}
                  value={this.searchText}
                  onChangeText={text => (this.searchText = text)}
                  placeholder={this.store.text.searchForYourFavoriteProducts}
                  placeholderTextColor={colors.borderLineColor}
                  style={{
                    fontSize: 10,
                    padding: 0,
                    margin: 0,
                    marginRight: 10,
                    marginLeft: 10,
                    color: 'black',
                  }}
                />
              </View>
              <View style={{ flexDirection: 'row', marginLeft: 6, marginTop: 5 }}>
                <Text style={{ fontSize: 10, color: colors.mainColor }}>
                  {this.store.text.popularSearches}
                </Text>
              </View>
            </View>
          </View>
        </View>
        <View
          style={{
            width: width - 40,
            height: 1,
            backgroundColor: colors.lineColor,
            margin: 20,
          }}
        />
        {this.renderResult()}
      </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 Search