import React, {Component} from 'react';
import {
  View,
  Text,
  ScrollView,
  TouchableHighlight,
  TouchableOpacity,
  Dimensions,
  Linking,
  FlatList,
  ImageBackground,
  StyleSheet,
  Image,
  Alert,
} from 'react-native';
import NaviBar from '../../components/navi-bar';
import history from '../../common/history';
var _ = require('lodash');
import {inject, observer} from 'mobx-react';
import LoadingView from '../../common/loading';
import Icon from 'react-native-vector-icons/FontAwesome5';
import {observable} from 'mobx';
import BackHeader from '../../components/backHeader';
import Icon2 from 'react-native-vector-icons/MaterialCommunityIcons';
import {width, height} from '../../common/screen';
import DeviceInfo from 'react-native-device-info';
import HistoryList from '../history/historyList';
import {Fonts} from '../../assets/styles/fonts-theme';
import Modal, {ModalContent} from 'react-native-modals';
import {colors} from '../../assets/styles/colors-theme';
import {scale, verticalScale, moderateScale} from 'react-native-size-matters';
import Menu, {
  MenuProvider,
  MenuTrigger,
  MenuOptions,
  MenuOption,
  renderers,
} from 'react-native-popup-menu';
const {SlideInMenu} = renderers;
const sortString = [
  {value: 0, label: '價錢低到高'},
  {value: 1, 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 OneClickRental extends Component {
  @observable oneClickApartment = [];
  @observable
  sort = 1;
  @observable
  areaA = ['全部'];
  @observable
  areaB = ['全部'];
  @observable
  areaAValue = '全部';
  @observable
  areaBValue = '全部';
  @observable
  areaAData = null;
  @observable
  dropdownListDisable = true;
  @observable
  selectApartmentalble = false;
  constructor(props) {
    super(props);
    this.store = props.appStore;
  }

  async componentWillMount() {
    await this.store.getOneClickRental();
    this.oneClickApartment = [...this.store.oneClickApartment];
    await this.sortAction();
    await this.getAreaA();
  }

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

  async getAreaA() {
    var array = ['全部'];
    await region.map((items, index) => {
      array.push(items.ch);
    });

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

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

  renderBackIcon() {
    return (
      <TouchableOpacity
        style={{
          justifyContent: 'center',
          alignItems: 'center',
          height: 40,
          width: 40,
          marginLeft: 20,
        }}
        onPress={() => {
          console.log('back');
          history.goBack(this);
        }}>
        <Icon
          name={'arrow-left'}
          size={22}
          color={'white'}
          style={{
            ...Platform.select({
              ios: {},
              android: {
                //  top: 40,
              },
            }),
          }}
        />
      </TouchableOpacity>
    );
  }

  renderavatar(items) {
    var data = _.cloneDeep(items);
    console.log(data);
    var avatarUriIndex = items.doc.findIndex(element => element.type === 1);
    if (avatarUriIndex !== -1) {
      return (
        <Image
          style={[
            {
              backgroundColor: '#F0F3F4',
              borderTopRightRadius: 15,
              borderTopLeftRadius: 15,
            },
            DeviceInfo.isTablet()
              ? {width: scale(275), height: verticalScale(320)}
              : {width: width - 20, height: verticalScale(150)},
          ]}
          //resizeMode={'contain'}
          source={{
            uri: items.doc[avatarUriIndex].uri,
          }}
        />
      );
    } else {
      return (
        <Image
          style={[
            {
              marginTop: 2,
              //width: scale(275),
              // height: verticalScale(200),
              borderTopRightRadius: 15,
              borderTopLeftRadius: 15,
              backgroundColor: '#F0F3F4',
            },
            DeviceInfo.isTablet()
              ? {width: scale(275), height: verticalScale(320)}
              : {width: width - 20, height: verticalScale(200)},
          ]}
          resizeMode={'cover'}
          source={require('../../assets/images/demohouse.png')}
        />
      );
    }
  }
  selectSort(items) {
    this.sort = items;
    this.sortAction();
  }

  dateStringHandler(date) {
    console.log(this.isValidDate(date));
    if (date === null) {
      return '';
    } else {
      if (this.isValidDate(date)) {
        return (
          date.getDate() +
          '/' +
          (date.getMonth() + 1) +
          '/' +
          date.getFullYear()
        );
      } else {
        return date;
      }
    }
  }

  isValidDate(date) {
    return (
      date &&
      Object.prototype.toString.call(date) === '[object Date]' &&
      !isNaN(date)
    );
  }

  rentdayreturn() {
    if (this.store.logined) {
      if (this.store.loginUserData.data.member.chara == 'owner') {
        return this.store.text.rentDay;
      } else {
        return this.store.text.payrentDay;
      }
    } else {
      return this.store.text.rentDay;
    }
  }

  renderOneClickApartment() {
    if (this.oneClickApartment.length > 0) {
      return this.oneClickApartment.map((items, index) => {
        return this.renderApartmentData(items, index);
      });
    }
  }
  renderApartmentData(items, index) {
    return (
      <View key={index} style={styles.slide1}>
        <View
          style={[
            styles.shadowView,
            DeviceInfo.isTablet() ? {width: scale(280)} : {width: width - 20},
          ]}>
          <TouchableOpacity>{this.renderavatar(items)}</TouchableOpacity>
          <View style={{marginLeft: 20, marginRight: 20}}>
            <Text style={[styles.text, {color: 'black'}]}>{items.name}</Text>

            <Text
              style={[styles.text, {fontSize: 17, fontFamily: Fonts.ubuntuTh}]}>
              {items.address}
            </Text>

            <View
              style={{
                flexDirection: 'row',
                flex: 1,
                height: 40,
                marginLeft: 5,
              }}>
              <View style={styles.subAddress}>
                <Text
                  style={{
                    fontSize: 17,
                    color: colors.textColor,
                    fontFamily: Fonts.ubuntuTh,
                  }}>
                  {this.store.text.floor}
                </Text>
                <Text
                  style={{
                    fontSize: 17,
                    fontFamily: Fonts.ubuntu,
                    marginLeft: 5,
                  }}>
                  {items.floor == '' ? '--' : items.floor}
                </Text>
              </View>
            </View>
            <View
              style={{backgroundColor: '#EDEFF0', width: width - 40, height: 1}}
            />
            {this.list(
              this.store.text.rent,
              'HKD ' + items.rent,
              colors.textColor,
            )}

            <View style={{flexDirection: 'row'}}>
              <View
                style={{
                  flexDirection: 'row',
                  marginRight: 5,
                  marginLeft: 5,
                  marginTop: 10,
                  flex: 0.5,
                  alignItems: 'center',
                }}>
                <View style={{}}>
                  <Text
                    style={{
                      fontFamily: Fonts.ubuntuTh,
                      color: colors.textColor,
                      fontSize: 20,
                    }}>
                    {'建築面積' + ':    '}
                  </Text>
                </View>
                <View style={{}}>
                  <Text
                    style={{
                      fontFamily: Fonts.ubuntuTh,
                      color: 'black',
                      fontSize: 20,
                    }}>
                    {/* {contents.length < 20
                    ? `${'-'}`
                    : `${'--'.substring(0, 40)}...`} */}
                    --
                  </Text>
                </View>
              </View>
              <View
                style={{
                  flexDirection: 'row',
                  marginRight: 5,
                  marginLeft: 5,
                  marginTop: 10,
                  flex: 0.5,
                  alignItems: 'center',
                }}>
                <View style={{}}>
                  <Text
                    style={{
                      fontFamily: Fonts.ubuntuTh,
                      color: colors.textColor,
                      fontSize: 20,
                    }}>
                    {'實用面積' + ':    '}
                  </Text>
                </View>
                <View style={{}}>
                  <Text
                    style={{
                      fontFamily: Fonts.ubuntuTh,
                      color: 'black',
                      fontSize: 20,
                    }}>
                    {/* {contents.length < 20
                    ? `${'-'}`
                    : `${'--'.substring(0, 40)}...`} */}
                    --
                  </Text>
                </View>
              </View>
            </View>
          </View>
          <View
            style={{
              backgroundColor: '#EDEFF0',
              width: width,
              height: 1,
              marginTop: 10,
            }}
          />
          <TouchableOpacity
            style={{
              marginTop: 20,
              marginBottom: 20,
              justifyContent: 'center',
              alignItems: 'center',
              flexDirection: 'row',
            }}
            onPress={() => {
              Alert.alert(
                '客服聯絡',
                '',
                [
                  {
                    text: '取消',
                    onPress: () => console.log('Cancel Pressed'),
                    style: 'cancel',
                  },
                  {
                    text: '致電 Rent Chat',
                    onPress: () => {
                      Linking.openURL(`tel:${'31040558'}`);
                    },
                  },
                ],
                {cancelable: false},
              );
            }}>
            <Icon name="comment" color={colors.textColor} size={30} solid />
            <Text
              style={{
                marginLeft: 10,
                fontFamily: Fonts.ubuntu,
                color: colors.textColor,
                fontSize: 19,
              }}>
              {'對樓盤有興趣？ 聯絡我們吧！'}
            </Text>
          </TouchableOpacity>
        </View>

        <View style={{width: width, height: 7, backgroundColor: '#EDEFF0'}} />
      </View>
    );
  }

  list(title, contents, color) {
    return (
      <View
        style={{
          flexDirection: 'row',
          marginRight: 5,
          marginLeft: 5,
          marginTop: 10,
          alignItems: 'center',
          width: scale(265),
        }}>
        <View style={{}}>
          <Text
            style={{
              fontFamily: Fonts.ubuntuTh,
              color: colors.textColor,
              fontSize: 20,
            }}>
            {title + ':    '}
          </Text>
        </View>
        <View style={{}}>
          <Text
            style={{fontFamily: Fonts.ubuntuTh, color: 'black', fontSize: 20}}>
            {contents.length < 20
              ? `${contents}`
              : `${contents.substring(0, 40)}...`}
          </Text>
        </View>
      </View>
    );
  }

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

      // this.repairData = repairData.filter(item => item.loc1 === value);
    } else {
      this.dropdownListDisable = false;
      var newData = await this.store.oneClickApartment.filter(function(item) {
        return item.region.parent.ch == value;
      });
      console.log(newData);
      this.oneClickApartment = [...newData];
      this.areaAData = [...newData];
      var array = ['全部'];

      var areaAIndex = await region.findIndex(element => element.ch == value);
      await region[areaAIndex].district.map((items, index) => {
        array.push(items.ch);
      });
      const uniqueSet = new Set(array);
      const backToArray = [...uniqueSet];
      this.areaB = backToArray;
    }
    this.sortAction();
  }

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

  oneClickRentalAction() {
    if (this.store.user != null) {
      if (this.store.logined) {
        if (this.store.loginUserData.data.member.chara == 'owner') {
          history.push(this, '/selectApartmentByOneClickRental');
        } else {
          Alert.alert(
            '一鍵放盤',
            '需要是業主的身份',
            [
              {
                text: '確定',
                onPress: () => console.log('Cancel Pressed'),
                style: 'cancel',
              },
            ],
            {cancelable: false},
          );
        }
      } else {
        Alert.alert(
          '一鍵放盤',
          '需要登入',
          [
            {
              text: '取消',
              onPress: () => console.log('Cancel Pressed'),
              style: 'cancel',
            },
            {
              text: '登入',
              onPress: () => {
                history.push(this, '/signin', {icon: true});
              },
            },
          ],
          {cancelable: false},
        );
      }
    } else {
      Alert.alert(
        '一鍵放盤',
        '需要成為業主並注冊會員',
        [
          {
            text: '取消',
            onPress: () => console.log('Cancel Pressed'),
            style: 'cancel',
          },
          {
            text: '成為業主',
            onPress: () => {
              var data = {
                type: 0,
                first: true,
              };
              this.props.navigation.navigate('Tutorial', {
                tutdata: data,
              });
            },
          },
        ],
        {cancelable: false},
      );
    }
  }

  render() {
    return (
      <MenuProvider style={{flex: 1}}>
        <LoadingView visible={this.store.loading} />
        <View
          style={{
            width: width,
            height: Platform.OS === 'ios' ? 65 : 80,
            backgroundColor: colors.mainColor,
            flexDirection: 'row',
            justifyContent: 'center',
            alignItems: 'center',
          }}>
          <View style={{flex: 1, justifyContent: 'center'}}>
            {this.renderBackIcon()}
          </View>

          <View
            style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
            <Text
              style={{fontFamily: Fonts.ubuntu, color: 'white', fontSize: 20}}>
              {this.store.text.oneClickRental}
            </Text>
          </View>
          <TouchableOpacity
            onPress={() => {
              // this.store.resetApartmentData();
              // history.push(this, '/simpleAddApartment');
              //  this.selectApartmentalble = true;
              // history.push(this, '/selectApartmentByOneClickRental');
              this.oneClickRentalAction();
            }}
            style={{flex: 1, justifyContent: 'center', alignItems: 'flex-end'}}>
            <Text
              style={{
                fontFamily: Fonts.ubuntu,
                color: 'white',
                fontSize: 17,
                marginRight: 20,
              }}>
              {'我要放盤'}
            </Text>
          </TouchableOpacity>
        </View>
        <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.scrollTo(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.scrollTo(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.scrollTo(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>
        <ScrollView
          style={{marginTop: 10}}
          ref={ref => {
            this.flatListRef = ref;
          }}>
          {this.renderOneClickApartment()}
        </ScrollView>
        <Modal
          visible={this.selectApartmentalble}
          width={0.7}
          height={0.7}
          onTouchOutside={() => {
            this.selectApartmentalble = false;
          }}
          swipeDirection={['up', 'down']} // can be string or an array
          swipeThreshold={200} // default 100
          onSwipeOut={event => {
            this.selectApartmentalble = false;
          }}>
          <ModalContent>
            <View
              style={{
                flexDirection: 'row',
                alignItems: 'center',
                justifyContent: 'center',
              }}></View>
          </ModalContent>
        </Modal>
      </MenuProvider>
    );
  }
}
const styles = StyleSheet.flatten({
  button: {
    marginTop: 20,
    width: 100,
    height: 40,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: colors.statusBarColor,
  },
  buttonText: {
    fontSize: 15,
    fontFamily: Fonts.ubuntu,
    color: 'white',
  },
  slide1: {
    justifyContent: 'center',
    alignItems: 'center',
  },

  shadowView: {backgroundColor: 'white', borderRadius: 15},
  buttonView: {
    backgroundColor: colors.mainColor,
    marginRight: 30,
    marginLeft: 30,
    marginTop: 30,
    marginBottom: 30,
    height: 40,
    width: 200,
    justifyContent: 'center',
    alignItems: 'center',
    borderRadius: 10,
  },

  apartmentText: {
    fontFamily: Fonts.ubuntuTh,
    color: colors.textColor,
    fontSize: 20,
  },
  text: {
    marginTop: 7,
    marginLeft: 5,
    color: colors.textColor,
    fontSize: 22,
    fontFamily: Fonts.ubuntu,
  },
  subAddress: {
    flex: 1,
    alignItems: 'center',
    flexDirection: 'row',
  },
});
