import React, {Component} from 'react';
import {
  View,
  Text,
  TouchableOpacity,
  StyleSheet,
  Image,
  FlatList,
  ScrollView,
} from 'react-native';
import FastImage from 'react-native-fast-image';
import Icon from 'react-native-vector-icons/FontAwesome5';
import Icon2 from 'react-native-vector-icons/MaterialCommunityIcons';
import {colors} from '../../assets/styles/colors-theme';
import {Fonts} from '../../assets/styles/fonts-theme';
import {SearchBar} from 'react-native-elements';
import history from '../../common/history';
import LoadingView from '../../common/loading';

import NaviBar from '../../components/navi-bar';
import {scale, verticalScale, moderateScale} from 'react-native-size-matters';
import Migrations from '../../services/realm/Mirgrations';
import {inject, observer} from 'mobx-react';
import BackHeader from '../../components/backHeader';
import {queryUser} from '../../services/realm/realmManger';
import PropertyList from './propertyList';
//import Swiper from 'react-native-swiper'
import Global from '../../services/Global';
import {width, height} from '../../common/screen';
import AddFunction from '../../common/addFunction';
import {
  UserSchemea,
  ApartmentSchemea,
  DocSchemea,
  NotificationSchemea,
} from '../../services/realm/schemeas';
import * as rssParser from 'react-native-rss-parser';
import Menu, {
  MenuProvider,
  MenuTrigger,
  MenuOptions,
  MenuOption,
  renderers,
} from 'react-native-popup-menu';
const {SlideInMenu} = renderers;
import Realm from 'realm';
import {observable, set} from 'mobx';
import {func} from 'prop-types';
let realm = new Realm({
  schema: [UserSchemea, ApartmentSchemea, DocSchemea, NotificationSchemea],
});
const sortString = [
  {value: 0, label: '價錢低到高'},
  {value: 1, label: '價錢高到低'},
  {value: 2, label: '日期新到舊'},
];

const region = [
  {
    ch: '香港島',
    en: 'Hong Kong Island',
    district: [
      {ch: '中西區', en: 'Central and Western'},
      {ch: '灣仔區', en: 'Wan Chai'},
      {ch: '東區', en: 'Eastern'},
      {ch: '南區', en: 'Southern'},
    ],
  },
  {
    ch: '九龍',
    en:'Kowloon',
    district: [
      {ch: '深水埗區', en: 'Sham Shui Po'},
      {ch: '油尖旺區', en: 'Yau Tsim Mong'},
      {ch: '九龍城區', en: 'Kowloon City'},
      {ch: '黃大仙區', en: 'Wong Tai Sin'},
      {ch: '觀塘區', en: 'Kwun Tong'},
    ],
  },
  {
    ch: '新界',
    en:'New Territories',
    district: [
      {ch: '葵青區',en:'Kwai Tsing'},
      {ch: '荃灣區',en:'Tsuen Wan'},
      {ch: '屯門區',en:'Tuen Mun'},
      {ch: '元朗區',en:'Yuen Long'},
      {ch: '北區',en:'North'},
      {ch: '大埔區',en:'Tai Po'},
      {ch: '沙田區',en:'Sha Tin'},
      {ch: '西貢區',en:'Sai Kung'},
      {ch: '離島區',en:'Islands'},
    ],
  },
];

@inject('appStore')
@observer
export default class Property extends Component<Props> {
  @observable
  news = [];
  @observable
  areaA = ['全部'];
  @observable
  areaB = ['全部'];
  @observable
  areaAValue = '全部';
  @observable
  areaBValue = '全部';
  @observable
  dropdownListDisable = true;
  @observable
  rentApartmentData = null;
  @observable
  areaAData = null;
  @observable
  sort = 2;
  @observable
  search = '';
  constructor(props) {
    super(props);
    this.store = props.appStore;
  }
  static navigationOptions = ({navigation}) => {
    const {params = {}} = navigation.state;
    return {
      tabBarLabel: params.handleThis,
    };
  };
  async componentWillMount() {
    //this.loadNews()
    await this.store.getRentInfo();
    this.rentApartmentData = [...this.store.rentApartmentData];
    this.sortAction();
    await this.getAreaA();
    this.props.navigation.setParams({
      handleThis: this.store.text.rentalInfo,
    });
  }

  sortAction() {
    if (this.sort == 0) {
      // this.rentApartmentData.sort((a, b) => (a.tprice > b.tprice ? 1 : -1));
      var newArray = [...this.rentApartmentData];
      this.rentApartmentData = newArray.sort((a, b) =>
        a.newprice > b.newprice ? 1 : b.newprice > a.newprice ? -1 : 0,
      );
      //this.rentApartmentData.sort(this.compare);
    } else if (this.sort == 1) {
      var newArray = [...this.rentApartmentData];
      this.rentApartmentData = newArray.sort((a, b) =>
        a.newprice < b.newprice ? 1 : b.newprice < a.newprice ? -1 : 0,
      );
    } else {
      var newArray = [...this.rentApartmentData];
      this.rentApartmentData = newArray.sort((a, b) =>
        a.newDate < b.newDate ? 1 : b.newDate < a.newDate ? -1 : 0,
      );
    }
  }

  updateSearch = search => {
    this.setState({search});
  };

  async getAreaA() {
    var array = ['全部'];
    await this.store.rentApartmentData.map((items, index) => {
      array.push(items.loc1);
    });

    const uniqueSet = new Set(array);
    const backToArray = [...uniqueSet];
    this.areaA = backToArray;

    //Array.from(new Set(array))
    console.log(backToArray);
  }

  async areaADropDownListOnSelect(value) {
    this.areaAValue = value;
    var index = this.areaA.findIndex(element => element == value);
    console.log(index);
    if (index == 0) {
      this.dropdownListDisable = true;
      this.rentApartmentData = [...this.store.rentApartmentData];
      this.areaAData = [...this.store.rentApartmentData];
      this.areaB = ['全部'];

      // this.repairData = repairData.filter(item => item.loc1 === value);
    } else {
      this.dropdownListDisable = false;
      var newData = await this.store.rentApartmentData.filter(function(item) {
        return item.loc1 == value;
      });
      this.rentApartmentData = [...newData];
      this.areaAData = [...newData];
      var array = ['全部'];
      await this.rentApartmentData.map((items, index) => {
        array.push(items.loc2);
      });
      const uniqueSet = new Set(array);
      const backToArray = [...uniqueSet];
      this.areaB = backToArray;
    }
    this.sortAction();
  }

  selectSort(items) {
    this.sort = items;
    this.sortAction();
  }

  SearchFilterFunction(text) {
    //passing the inserted text in textinput
    const newData = this.store.rentApartmentData.filter(function(item) {
      //applying filter for the inserted text in search bar
      const itemData = item.estate;
      const textData = text;
      return itemData.indexOf(textData) > -1;
    });
    this.rentApartmentData = [...newData];
    this.search = text;
    this.sortAction();
  }

  async areaBDropDownListOnSelect(value) {
    this.areaBValue = value;
    var index = this.areaB.findIndex(element => element == value);
    if (index == 0) {
      this.rentApartmentData = [...this.areaAData];
      // this.repairData = repairData.filter(item => item.loc1 === value);
    } else {
      var newData = await this.areaAData.filter(function(item) {
        return item.loc2 == value;
      });
      this.rentApartmentData = [...newData];
    }
    this.sortAction();
  }

  render() {
    return (
      <MenuProvider style={styles.container}>
        <LoadingView visible={this.store.loading} />
        <BackHeader
          title={
            this.store.text.rentalInfo + '(' + this.store.text.housing + ')'
          }
          back={true}
          instance={this}
        />
        <SearchBar
          placeholder={this.store.text.search}
          containerStyle={{
            backgroundColor: 'white',
            borderColor: colors.mainColor,
            borderTopWidth: 0,
            borderBottomWidth: 0,
          }}
          onChangeText={text => {
            this.SearchFilterFunction(text);
          }}
          onClear={text => this.SearchFilterFunction('')}
          inputContainerStyle={{backgroundColor: '#F1EDED', borderRadius: 10}}
          value={this.search}
        />
        <View
          style={{
            width: width,
            height: 50,
            flexDirection: 'row',
            alignItems: 'center',
          }}>
          <View
            style={{
              flex: 0.4,
              marginLeft: 10,
              flexDirection: 'row',
              alignItems: 'center',
            }}>
            
            <Menu
              name="area1"
              renderer={SlideInMenu}
              onSelect={value => {
                this.areaADropDownListOnSelect(value);
                this.flatListRef.scrollToOffset({animated: true, offset: 0});
              }}>
              <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.mainColor,
                      marginLeft: 5,
                      fontFamily: Fonts.ubuntu,
                    }}>
                    {this.store.text.region}
                  </Text>
                  <Text
                    style={{
                      fontFamily: Fonts.ubuntu,
                      color: colors.mainColor,
                      marginLeft: 5,
                    }}>
                    {this.areaAValue}
                  </Text>
                </View>
              </MenuTrigger>
              <MenuOptions
                customStyles={{
                  optionText: {
                    margin: 5,
                    fontFamily: Fonts.ubuntu,
                    color: 'white',
                    fontSize: 20,
                  },
                  optionWrapper: {
                    backgroundColor: colors.mainColor,
                    alignItems: 'center',
                  },
                }}>
                {this.areaA.map((obj, i) => {
                  return <MenuOption value={obj} text={obj} />;
                })}
              </MenuOptions>
            </Menu>
          </View>
          <View
            style={{
              flex: 0.4,
              flexDirection: 'row',
              alignItems: 'center',
            }}>
 
            <Menu
              name="area2"
              renderer={SlideInMenu}
              onSelect={value => {
                this.areaBDropDownListOnSelect(value);
                this.flatListRef.scrollToOffset({animated: true, offset: 0});
              }}>
              <MenuTrigger
                disabled={this.dropdownListDisable}
                style={{flexDirection: 'row'}}>
                <View
                  style={{
                    alignItems: 'center',
                    justifyContent: 'center',
                    flexDirection: 'row',
                  }}>
                  <Icon
                    name="map-marker-alt"
                    color={colors.mainColor}
                    size={17}
                  />
                  <Text
                    style={{
                      fontFamily: Fonts.ubuntu,
                      color: colors.mainColor,
                      marginLeft: 5,
                    }}>
                    {this.store.text.district}
                  </Text>
                  <Text
                    style={{
                      fontFamily: Fonts.ubuntu,
                      color: colors.mainColor,
                      marginLeft: 5,
                    }}>
                    {this.areaBValue}
                  </Text>
                </View>
              </MenuTrigger>
              <MenuOptions
                customStyles={{
                  optionText: {
                    margin: 5,
                    fontFamily: Fonts.ubuntu,
                    color: 'white',
                    fontSize: 20,
                  },
                  optionWrapper: {
                    backgroundColor: colors.mainColor,
                    alignItems: 'center',
                  },
                }}>
                <ScrollView style={{maxHeight: 300}}>
                  {this.areaB.map((obj, i) => {
                    return <MenuOption value={obj} text={obj} />;
                  })}
                </ScrollView>
              </MenuOptions>
            </Menu>
          </View>
          <View
            style={{
              flex: 0.2,
              flexDirection: 'row',
              alignItems: 'center',
            }}>
            <Menu
              name="sort"
              renderer={SlideInMenu}
              onSelect={value => {
                // this.areaBDropDownListOnSelect(value);
                console.log(value);
                this.selectSort(value);
                this.flatListRef.scrollToOffset({animated: true, offset: 0});
              }}>
              <MenuTrigger
                style={{
                  flexDirection: 'row',
                  justifyContent: 'center',
                  alignItems: 'center',
                }}>
                <Icon2 name="sort" color={colors.mainColor} size={25} />
                <Text
                  style={{
                    color: colors.mainColor,
                    marginLeft: 5,
                    fontFamily: Fonts.ubuntu,
                  }}>
                  排序
                </Text>
              </MenuTrigger>
              <MenuOptions
                customStyles={{
                  optionText: {
                    margin: 5,
                    fontFamily: Fonts.ubuntu,
                    color: 'white',
                    fontSize: 20,
                  },
                  optionWrapper: {
                    backgroundColor: colors.mainColor,
                    alignItems: 'center',
                  },
                }}>
                {sortString.map((obj, i) => {
                  return <MenuOption value={obj.value} text={obj.label} />;
                })}
              </MenuOptions>
            </Menu>
          </View>
        </View>

        <FlatList
          ref={ref => {
            this.flatListRef = ref;
          }}
          data={this.rentApartmentData}
          renderItem={({item}) => (
            <PropertyList
              items={item}
              // onPress={() => {
              //   history.push(this, '/propertyDetails', {rentData: item});
              // }}
            />
          )}
          keyExtractor={item => item.id}
        />
      </MenuProvider>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: 'white',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  button: {
    borderWidth: 1,
    borderColor: '#000000',
    margin: 5,
    padding: 5,
    width: '70%',
    backgroundColor: '#DDDDDD',
    borderRadius: 5,
  },
  textField: {
    borderWidth: 1,
    borderColor: '#AAAAAA',
    margin: 5,
    padding: 5,
    width: '70%',
  },
  spacer: {
    height: 10,
  },
  title: {
    fontWeight: 'bold',
    fontSize: 20,
    textAlign: 'center',
  },
});
