import React, {Component} from 'react';
import {
  View,
  Text,
  TouchableHighlight,
  StyleSheet,
  TouchableOpacity,
  ScrollView,
  Alert,
  Image,
  Linking,
} from 'react-native';
import {KeyboardAwareScrollView} from 'react-native-keyboard-aware-scroll-view';
import Switch from 'react-native-switch-pro';
import history from '../../common/history';
import NaviBar from '../../components/navi-bar';
import Modal, {ModalContent} from 'react-native-modals';
import {Avatar} from 'react-native-elements';
import Global from '../../services/Global';
import {scale, verticalScale, moderateScale} from 'react-native-size-matters';
import RadioForm, {
  RadioButton,
  RadioButtonInput,
  RadioButtonLabel,
} from 'react-native-simple-radio-button';
import {NavigationActions} from 'react-navigation';
import Swiper from 'react-native-swiper';
import Icon from 'react-native-vector-icons/FontAwesome5';
import CheckAnimate from '../../common/checkAnimate';
import Toast, {DURATION} from 'react-native-easy-toast';
import {Dropdown} from 'react-native-material-dropdown';
import {colors} from '../../assets/styles/colors-theme';
import {Fonts} from '../../assets/styles/fonts-theme';
import BackHeader from '../../components/backHeader';
import CommonTextInput from '../../components/commonTextInput';
import {inject, observer} from 'mobx-react';
import {observable} from 'mobx';
import {width, height} from '../../common/screen';
import Size from '../../common/size';
const size = new Size();

var radio_props = [
  {label: 'English', value: 'english'},
  {label: '繁體中文', value: 'hk'},
  {label: '简体中文', value: 'ch'},
];

@inject('appStore')
@observer
export default class Profile extends Component {
  @observable swiperIndex = 0;
  @observable notification = true;
  @observable dialogLanguageVisable = false;
  @observable dialogInputVisable = false;
  @observable changeCharVisable = false;
  @observable languageIndex = 0;
  constructor(props) {
    super(props);
    this.store = props.appStore;
  }

  componentWillMount() {
    switch (this.store.languageSelection) {
      case 'english':
        this.languageIndex = 0;
        break;
      case 'hk':
        this.languageIndex = 1;
        break;
      case 'ch':
        this.languageIndex = 2;
        break;
    }
  }

  switchInfoAndSetting(index) {
    console.log('index: ' + index);
    console.log('swiper index: ' + this.swiperIndex);
    if (index == 0) {
      if (this.swiperIndex === 1) {
        console.log('test');
        this._swiper.scrollBy(-1);
      }
    } else if (index === 1) {
      if (this.swiperIndex !== 1) {
        this._swiper.scrollBy(1);
      }
    }
  }

  settingAction(action) {
    switch (action) {
      case 'language':
        this.dialogLanguageVisable = true;
        console.log(this.dialogLanguageVisable);

        break;

      case 'creditCard':
        history.push(this, '/card');
        break;

      case 'signature':
        if (this.store.loginUserData.data.member.hasOwnProperty('sign')) {
          this.store.signUri = this.store.loginUserData.data.member.sign;
        }
        if (this.store.loginUserData.data.member.hasOwnProperty('stamp')) {
          this.store.stampUri = this.store.loginUserData.data.member.stamp;
        }
        history.push(this, '/signatureView', {
          imageUri: this.store.loginUserData.data.member.sign,
        });
        break;
      case 'changechar':
        if (this.store.loginUserData != null) {
          this.refs.toast.show(this.store.text.plbctc);
        } else {
          // this.props.navigation.navigate("SelectChar",{change:true});
          this.changeCharVisable = true;
        }
        break;

      case 'tutorial':
        var data = {
          type: this.store.user.memberType,
          first: false,
        };
        this.props.navigation.navigate('Tutorial', {
          tutdata: data,
        });
        break;

      case 'privacy':
        Linking.openURL('https://rent-chat.com/terms-conditions.html#private');
        break;

      case 'terms':
       this.store.genNonce()
        // Linking.openURL('https://rent-chat.com/terms-conditions.html');
        break;
      case 'logout':
        this.logoutAction();
        break;
      case 'login':
        history.push(this, '/signin', {
          icon: true,
          backToHome: this.backToHome,
        });
        break;
    }
  }

  backToHome = back => {
    if (back) {
      console.log('backtohome');
      // this.props.navigation.navigate('home');
      this.store.CheckWhichLocalApartmentNotSync(this);
    }
  };

  async clickAction() {
    await this.store.startAnimate();
    await history.push(this, '/news');
    // this.store.animateStatus.show = false;
  }
  logoutAction() {
    Alert.alert(
      '',
      this.store.text.austlo,
      [
        {
          text: this.store.text.cancel,
          onPress: () => console.log('Cancel Pressed'),
          style: 'cancel',
        },
        {
          text: this.store.text.sure,
          onPress: () => {
            this.store.logoutPost(this, false, {});
          },
        },
      ],
      {cancelable: false},
    );
  }

  inputAction(action) {
    switch (action) {
      case 'phone':
        break;

      case 'phone':
        break;

      case 'phone':
        break;
    }
  }

  renderMain() {
    const logoutSettingList = [
      {title: this.store.text.language, switch: false, action: 'language'},

      {
        title: this.store.text.notification,
        switch: true,
        action: 'notification',
      },
      {title: this.store.text.changechar, switch: false, action: 'changechar'},
      {title: this.store.text.tutorial, switch: false, action: 'tutorial'},
      {title: this.store.text.privacy, switch: false, action: 'privacy'},
      {title: this.store.text.terms, switch: false, action: 'terms'},
      {title: this.store.text.signin, switch: false, action: 'login'},
    ];
    const settingList = [
      {title: this.store.text.language, switch: false, action: 'language'},
      {
        title: this.store.text.creditCard,
        switch: false,
        action: 'creditCard',
      },
      {
        title: this.store.text.signature,
        switch: false,
        action: 'signature',
      },
      {
        title: this.store.text.notification,
        switch: true,
        action: 'notification',
      },
      {title: this.store.text.changechar, switch: false, action: 'changechar'},
      {title: this.store.text.tutorial, switch: false, action: 'tutorial'},
      {title: this.store.text.privacy, switch: false, action: 'privacy'},
      {title: this.store.text.terms, switch: false, action: 'terms'},
      {title: this.store.text.logout, switch: false, action: 'logout'},
    ];
    if (this.store.logined) {
      return (
        <View style={{alignItems: 'center'}}>
          <View
            style={{width: width - 40, flexDirection: 'row', marginTop: 20}}>
            <View style={{marginLeft: 30}}>
              <Text style={[styles.textView, {marginTop: 10}]}>
                {this.store.loginUserData.data.member.fullname}
              </Text>
              <Text style={[styles.textView, {marginTop: 5}]}>
                {this.store.loginUserData.data.member.chara}
              </Text>
            </View>
          </View>
          <View
            style={{
              width: width - 30,
              height: 90,
              marginTop: 30,
              flexDirection: 'row',
              justifyContent: 'center',
              alignItems: 'center',
            }}>
            <View style={[styles.midInfoView]}>
              <Text style={styles.numberTextView}>
                {this.store.apartmentsData.length}
              </Text>
              <Text style={[styles.textView, {marginTop: 10}]}>
                {this.store.text.property}
              </Text>
            </View>

            <View
              style={{
                height: 40,
                width: 1,
                borderLeftWidth: 1,
                borderColor: colors.textColor,
              }}
            />
            <View style={[styles.midInfoView]}>
              <Text style={styles.numberTextView}>0</Text>
              <Text style={[styles.textView, {marginTop: 10}]}>
                {this.store.text.coupons}
              </Text>
              <Icon
                style={{position: 'absolute', top: 0, right: 10}}
                name={'share-alt'}
                color={colors.mainColor}
                size={32}
              />
            </View>
          </View>
          <View
            style={{
              flexDirection: 'row',
              justifyContent: 'center',
              alignItems: 'center',
              width: width - 80,
            }}>
            <TouchableOpacity
              onPress={() => {
                this.switchInfoAndSetting(0);
              }}
              style={{
                flex: 1,
                height: 30,
                justifyContent: 'center',
                alignItems: 'center',
                borderWidth: 0.5,
                borderColor: colors.textColor,
                borderTopLeftRadius: 6,
                borderBottomLeftRadius: 6,
                backgroundColor:
                  this.swiperIndex === 0 ? colors.mainColor : 'white',
              }}>
              <Text
                style={{
                  color: this.swiperIndex === 0 ? 'white' : colors.textColor,
                  fontSize: 12,
                  fontFamily: Fonts.ubuntu,
                }}>
                {this.store.text.information}
              </Text>
            </TouchableOpacity>
            <TouchableOpacity
              onPress={() => {
                this.switchInfoAndSetting(1);
              }}
              style={{
                flex: 1,
                height: 30,
                justifyContent: 'center',
                alignItems: 'center',
                borderWidth: 0.5,
                borderColor: colors.textColor,
                borderTopRightRadius: 6,
                borderBottomRightRadius: 6,
                backgroundColor:
                  this.swiperIndex === 1 ? colors.mainColor : 'white',
              }}>
              <Text
                style={{
                  color: this.swiperIndex === 1 ? 'white' : colors.textColor,
                  fontSize: 12,
                  fontFamily: Fonts.ubuntu,
                }}>
                {this.store.text.setting}
              </Text>
            </TouchableOpacity>
          </View>

          <Swiper
            style={{height: verticalScale(460)}}
            showsButtons={false}
            showsPagination={false}
            ref={swiper => {
              this._swiper = swiper;
            }}
            loop={false}
            onIndexChanged={index => {
              (this.swiperIndex = index), console.log(this.swiperIndex);
            }}>
            <View style={styles.slide1}>
              <TouchableOpacity
                style={styles.settingTextView}
                onPress={() => {
                  if (this.store.loginUserData.data.member.phone == null) {
                    var data = {
                      vercode: '',
                      fullname: '',
                      email: '',
                      gender: 'na',
                      countryCode: '852',
                      chara: 'owner',
                      age: 'na',
                      thirdParty: true,
                      pwd: '',
                      phone: '',
                      refcode: '',
                      ownerPhone: '', // 如果char係租客就會有，OWNER就NULL
                    };
                    history.push(this, '/signUpVerify', {
                      signupData: data,
                      addphone: true,
                    });
                  }
                }}>
                <View style={styles.settingLeftTextView}>
                  <Text style={styles.settingLeftText}>
                    {this.store.text.phonenumber}
                  </Text>
                </View>
                <View style={styles.settingRightTextView}>
                  <Text style={styles.settingRightText}>
                    {this.store.loginUserData.data.member.phone == null
                      ? this.store.text.clickHereToEnterYourMobile
                      : '+' +
                        this.store.loginUserData.data.member.countryCode +
                        ' ' +
                        this.store.loginUserData.data.member.phone}
                  </Text>
                  <Icon name={'edit'} size={20} color={colors.textColor} />
                </View>
              </TouchableOpacity>

              <View style={styles.settingTextView}>
                <View style={styles.settingLeftTextView}>
                  <Text style={styles.settingLeftText}>
                    {this.store.text.email}
                  </Text>
                </View>
                <View style={styles.settingRightTextView}>
                  <Text style={styles.settingRightText}>
                    {this.store.loginUserData.data.member.email}
                  </Text>
                  {/* <Icon name={'edit'} size={20} color={colors.textColor} /> */}
                </View>
              </View>

              <View style={styles.settingTextView}>
                <View style={styles.settingLeftTextView}>
                  <Text style={styles.settingLeftText}>
                    {this.store.text.password}
                  </Text>
                </View>
                <View style={styles.settingRightTextView}>
                  <Text style={styles.settingRightText}>********</Text>
                  {/* <Icon name={'edit'} size={20} color={colors.textColor} /> */}
                </View>
              </View>

              <View
                style={{
                  borderBottomColor: colors.textColor,
                  marginTop: 10,
                  height: verticalScale(40),
                  borderRadius: 5,
                  flexDirection: 'row',
                  width: width - 30,
                  alignItems: 'center',
                }}>
                <TouchableOpacity onPress={() => this.clickAction()}>
                  <Text style={styles.settingLeftText}>Version: 1.1</Text>
                </TouchableOpacity>
              </View>
            </View>
            <View style={styles.slide1}>
              {settingList.map((items, index) => {
                if (items.switch) {
                  return (
                    <TouchableOpacity style={styles.settingTextView}>
                      <View style={styles.settingLeftTextView}>
                        <Text style={styles.settingLeftText}>
                          {items.title}
                        </Text>
                      </View>
                      <View style={styles.settingRightTextView}>
                        <Switch
                          value={this.notification}
                          backgroundActive={colors.mainColor}
                          onSyncPress={value => {
                            (this.notification = value),
                              console.log(value + '   ' + this.notification);
                          }}
                        />
                      </View>
                    </TouchableOpacity>
                  );
                } else {
                  return (
                    <TouchableOpacity
                      style={styles.settingTextView}
                      onPress={() => {
                        this.settingAction(items.action);
                      }}>
                      <View style={styles.settingLeftTextView}>
                        <Text style={styles.settingLeftText}>
                          {items.title}
                        </Text>
                      </View>
                      <View style={styles.settingRightTextView}>
                        <Icon
                          name={'chevron-right'}
                          size={20}
                          color={colors.textColor}
                        />
                      </View>
                    </TouchableOpacity>
                  );
                }
              })}
            </View>
          </Swiper>
        </View>
      );
    } else {
      return (
        <View style={{alignItems: 'center'}}>
          <View style={styles.slide1}>
            {logoutSettingList.map((items, index) => {
              if (items.switch) {
                return (
                  <TouchableOpacity style={styles.settingTextView}>
                    <View style={styles.settingLeftTextView}>
                      <Text style={styles.settingLeftText}>{items.title}</Text>
                    </View>
                    <View style={styles.settingRightTextView}>
                      <Switch
                        value={this.notification}
                        backgroundActive={colors.mainColor}
                        onSyncPress={value => {
                          (this.notification = value),
                            console.log(value + '   ' + this.notification);
                        }}
                      />
                    </View>
                  </TouchableOpacity>
                );
              } else {
                return (
                  <TouchableOpacity
                    style={styles.settingTextView}
                    onPress={() => {
                      this.settingAction(items.action);
                    }}>
                    <View style={styles.settingLeftTextView}>
                      <Text style={styles.settingLeftText}>{items.title}</Text>
                    </View>
                    <View style={styles.settingRightTextView}>
                      <Icon
                        name={'chevron-right'}
                        size={20}
                        color={colors.textColor}
                      />
                    </View>
                  </TouchableOpacity>
                );
              }
            })}
          </View>
        </View>
      );
    }
  }

  render() {
    return (
      <View style={{flex: 1, backgroundColor: 'white'}}>
        <CheckAnimate
          visible={this.store.animateStatus.show}
          progress={this.store.animateStatus.progress}
        />
        <NaviBar
          title={'Home'}
          self={this}
          onPress={() => {
            if (this.store.logined) {
              this.store.gotohelperChat(this);
            } else {
              // const navigateAction = NavigationActions.navigate({
              //   routeName: 'home',
              //   action: NavigationActions.navigate({ routeName: 'home' }),
              // });
              // this.props.navigation.dispatch(navigateAction);
              this.props.navigation.navigate('home');
            }
          }}
        />
        <ScrollView>{this.renderMain()}</ScrollView>
        <Modal
          visible={this.dialogLanguageVisable}
          width={0.5}
          height={0.25}
          onTouchOutside={() => {
            this.dialogLanguageVisable = false;
          }}
          swipeDirection={['up', 'down']} // can be string or an array
          swipeThreshold={200} // default 100
          onSwipeOut={event => {
            this.dialogLanguageVisable = false;
          }}>
          <ModalContent>
            <View>
              <RadioForm formHorizontal={false} animation={true}>
                {radio_props.map((obj, i) => {
                  return (
                    <RadioButton labelHorizontal={true} key={i}>
                      <RadioButtonInput
                        obj={obj}
                        index={this.languageIndex}
                        isSelected={this.languageIndex === i}
                        onPress={() => {
                          this.languageIndex = i;
                          this.store.changeLanguage(obj.value);
                          console.log(this.languageIndex);
                        }}
                        borderWidth={1}
                        buttonInnerColor={colors.mainColor}
                        buttonOuterColor={
                          this.languageIndex === i
                            ? colors.mainColor
                            : colors.textColor
                        }
                        buttonSize={15}
                        buttonOuterSize={30}
                        buttonStyle={{}}
                        buttonWrapStyle={{marginLeft: 10}}
                      />
                      <RadioButtonLabel
                        obj={obj}
                        index={this.languageIndex}
                        labelHorizontal={true}
                        onPress={() => {
                          this.languageIndex = i;
                          this.store.changeLanguage(obj.value);
                        }}
                        labelStyle={{
                          fontSize: 14,
                          color: colors.textColor,
                          fontFamily: Fonts.ubuntu,
                        }}
                        labelWrapStyle={{}}
                      />
                    </RadioButton>
                  );
                })}
              </RadioForm>
            </View>
          </ModalContent>
        </Modal>
        <Modal
          visible={this.changeCharVisable}
          width={0.7}
          height={0.5}
          onTouchOutside={() => {
            this.changeCharVisable = false;
          }}
          swipeDirection={['up', 'down']} // can be string or an array
          swipeThreshold={200} // default 100
          onSwipeOut={event => {
            this.changeCharVisable = false;
          }}>
          <ModalContent style={{backgroundColor: colors.mainColor}}>
            <View
              style={{
                backgroundColor: colors.mainColor,
                alignItems: 'center',
              }}>
              <TouchableOpacity
                style={{
                  justifyContent: 'center',
                  alignItems: 'center',
                  marginTop: 20,
                }}
                onPress={() => {
                  this.changeCharVisable = false;
                  this.store.changeChar(this, 0);
                }}>
                <Image
                  source={require('../../assets/images/owner.png')}
                  overlayColor={colors.mainColor}
                />

                <Text style={[styles.textStyle, {marginTop: 10}]}>
                  {this.store.text.owner}
                </Text>
              </TouchableOpacity>

              <TouchableOpacity
                style={{
                  height: 200,
                  width: 200,
                  marginTop: 20,
                  justifyContent: 'center',
                  alignItems: 'center',
                }}
                onPress={() => {
                  this.changeCharVisable = false;
                  this.store.changeChar(this, 1);
                }}>
                <Image source={require('../../assets/images/tenant.png')} />

                <Text style={[styles.textStyle, {marginTop: 10}]}>
                  {this.store.text.tenant}
                </Text>
              </TouchableOpacity>
            </View>
          </ModalContent>
        </Modal>
        <Toast
          ref="toast"
          style={{backgroundColor: colors.mainColor}}
          position="center"
          positionValue={200}
          fadeInDuration={750}
          fadeOutDuration={2000}
          opacity={0.8}
          textStyle={{color: 'white'}}
        />
      </View>
    );
  }
}

const styles = StyleSheet.flatten({
  textView: {
    color: colors.textColor,
    fontFamily: Fonts.ubuntu,
    fontSize: 17,
  },

  midInfoView: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  numberTextView: {
    color: colors.textColor,
    fontFamily: Fonts.ubuntu,
    fontSize: 20,
  },
  smallIconView: {
    position: 'absolute',
    top: 0,
    right: 10,
  },
  slide1: {
    alignItems: 'center',
    flex: 1,
  },
  slide2: {
    justifyContent: 'center',
    alignItems: 'center',
  },

  settingTextView: {
    borderBottomColor: colors.textColor,
    borderBottomWidth: 1,
    marginTop: 10,
    height: verticalScale(40),
    borderRadius: 5,
    flexDirection: 'row',
    width: width - 30,
    alignItems: 'center',
  },
  settingLeftTextView: {
    alignItems: 'flex-start',
    flex: 0.4,
  },
  settingRightTextView: {
    justifyContent: 'flex-end',
    alignItems: 'center',
    flexDirection: 'row',
    flex: 0.6,
  },
  settingLeftText: {
    color: colors.textColor,
    fontSize: 15,
    fontFamily: Fonts.ubuntuL,
  },
  settingRightText: {
    color: colors.textColor,
    fontSize: 15,
    fontFamily: Fonts.ubuntuL,
    alignItems: 'flex-start',
    marginRight: 10,
  },
  textStyle: {
    color: 'white',
    fontFamily: Fonts.ubuntu,
    fontSize: 14,
  },
});
