import React from 'react';
import {
  SafeAreaView,
  Text,
  View,
  TouchableOpacity,
  StyleSheet,
  Image,
  ScrollView,
  Share,
  Alert,
  Linking,
} from 'react-native';
var _ = require('lodash');
import Modal from 'react-native-modal';
import Toast, { DURATION } from 'react-native-easy-toast';
import Switch from 'react-native-switch-pro';
import { width, height } from '../../services/screen';
import { images } from '../../assets/images/imageIndex';
import AsyncStorage from '@react-native-community/async-storage';
import Loading from '../../components/Loading';
import { inject, observer } from 'mobx-react';
import { colors } from '../../assets/styles/colors-theme';
import Rank from '../../components/rank';
import TitleBar from '../../components/titleBar';
import HTMLView from 'react-native-htmlview';
import CustomLoginButton from '../../components/customLoginButton';
import { getStatusBarHeight } from 'react-native-status-bar-height';
import { observable } from 'mobx';
import Icon from 'react-native-vector-icons/dist/MaterialCommunityIcons';
import FeatherIcon from 'react-native-vector-icons/dist/Feather';
import FontAwesomeIcon from 'react-native-vector-icons/dist/FontAwesome';
//import Adyen from 'adyen-react-native';
import Menu, {
  MenuProvider,
  MenuTrigger,
  MenuOptions,
  MenuOption,
  renderers,
} from 'react-native-popup-menu';
const { SlideInMenu } = renderers;
const langList = [
  { label: '繁體中文', value: 'hk' },
  { label: 'English', value: 'en' },
  { label: '簡體中文', value: 'zh' }
];
const API_KEY =
  //'AQEhhmfuXNWTK0Qc+iSem3Y3qfffgjkjOauoEZcB7q2DToV3EMFdWw2+5HzctViMSCJMYAc=-kpW/CqOWAmOBWEEhFHdHKKV/dcUBco7qbCGV+/U6KDE=-F?6e&d8kq%7)?D6H';
  'AQEkhmfuXNWTK0Qc+iSem3Y3qffCENhaJNh8FEMlEb7DNf3Ae1UzEMFdWw2+5HzctViMSCJMYAc=-SmX/AHu3xTVV2+Uek0ZHC2MxuW1df26lENMn6T4DVPw=-f3A?_6;kbd&pgK4g';
const MERCHANT_ACCOUNT =
  //'NironsECOM';
  'Nirons983ECOM';
FontAwesomeIcon.loadFont();
@inject('appStore')
@observer
export default class Setting extends React.Component {
  @observable notification = true;
  @observable lang = '繁體中文';
  @observable introVisable = false

  @observable
  data = [
    {
      title: 'name',
      icon: 'account',
      content: this.store.loginUserData.data.display_name,
      width1: 0.2,
      width2: 0.8,
    },
    {
      title: 'email',
      icon: 'email',
      content: this.store.loginUserData.data.email,
      width1: 0.2,
      width2: 0.8,
    },
    {
      title: 'mobilephone',
      icon: 'phone',
      content:
        this.store.loginUserData.data.country_code +
        ' ' +
        this.store.loginUserData.data.mobile,
      width1: 0.3,
      width2: 0.7,
    },
    {
      title: 'points',
      icon: 'gift',
      content: this.store.points,
      width1: 0.5,
      width2: 0.5,
    },
    {
      title: 'address',
      icon: 'store',
      content: this.addressReturn(),
      width1: 0.2,
      width2: 0.8,
    },
  ];
  constructor(props) {
    super(props);
    this.store = props.appStore;
    // Adyen.onRequestPaymentSession(this.onRequestPaymentSession);
    // Adyen.onPaymentResult((code, payload) =>{
    //   this.setState({status: 'success'}),
    //   console.log(code)
    //   console.log(payload)
    // }
    // );
    // Adyen.onError((code, error) => this.setState({status: 'failure'}));
  }

  // onRequestPaymentSession(token, returnUrl) {
  //   console.log(token, returnUrl);
  //   fetch('https://checkout-test.adyen.com/v41/paymentSession', {
  //     method: 'POST',
  //     headers: {
  //       'Content-Type': 'application/json',
  //       'x-API-key': API_KEY,
  //     },
  //     body: JSON.stringify({
  //       amount: {
  //         value: 1747,
  //         currency: 'HKD',
  //       },
  //       reference: 'Test payments',
  //       countryCode: 'HK',
  //       shopperReference: 'demo@demo.com',
  //       returnUrl: 'return-url://',
  //       token,
  //       merchantAccount: MERCHANT_ACCOUNT,
  //     }),
  //   })
  //     .then(response => response.json())
  //     .then(responseData => Adyen.confirmPayment(responseData.paymentSession))
  //     .done();
  // }

  async selectLangAction(value) {
    console.log(value);
    this.store.changeLanguage(value.value);
    this.lang = value.label;
    try {
      await AsyncStorage.setItem('lang', value.value);
    } catch (e) {
      // saving error
    }
  }

  async componentWillMount() {
    await this.store.getPoints();
    this.data[0].content = this.store.loginUserData.data.display_name;
    this.data[1].content = this.store.loginUserData.data.email;
    this.data[2].content =
      this.store.loginUserData.data.country_code +
      ' ' +
      this.store.loginUserData.data.mobile;
    this.data[4].content = this.addressReturn();
    try {
      const value = await AsyncStorage.getItem('lang');
      if (value !== null) {
        console.log(value);
        if (value == 'hk') {
          this.lang = '繁體中文';
        } else if (value == 'en') {
          this.lang = 'English';
        } else {
          this.lang = '簡體中文';
        }
      } else {
        this.lang = '繁體中文';
      }
    } catch (e) {
      // error reading value
    }
  }

  addressReturn() {
    // if (this.store.loginUserData.data.shipping.address_1 != '') {
    //   return (
    //     this.store.loginUserData.data.shipping.address_1 +
    //     ', ' +
    //     this.store.loginUserData.data.shipping.address_2
    //   );
    // } else {
    //return this.store.text.clickHereToEnterTheAddress;
    //}
    if (this.store.addresses.length > 0) {
      return (
        this.store.addresses[0].region.name +
        ', ' +
        this.store.addresses[0].district.name +
        ', ' +
        this.store.addresses[0].address
      );
    } else {
      return this.store.text.clickHereToEnterTheAddress;
    }
  }

  userDataClickAction(index) {
    switch (index) {
      case 0:
        this.props.navigation.navigate('AddName');
        break;
      case 4:
        this.props.navigation.navigate('AddressSetting');
        break;
      case 2:
        if (this.store.loginUserData.data.mobile == null) {
          this.props.navigation.navigate('SignUpVerify', {
            data: {
              first_name: '',
              last_name: '',
              welcome_code: '',
              country_code: '+852',
              mobile: '',
              email: '',
              ver_code: '',
              password: '',
            },
            addMobile: true,
          });
        } else {
        }
        break;
    }
  }

  titleStringReturn(title) {
    switch (title) {
      case 'name':
        return this.store.text.name;
        break;
      case 'email':
        return this.store.text.email;
        break;
      case 'mobilephone':
        return this.store.text.mobilephone;
        break;
      case 'points':
        return this.store.text.points;
        break;
      case 'address':
        return this.store.text.address;
        break;
    }
  }

  share() {
    Share.share({
      message:
        '本公司專門為客人從日本空運到港 提供最新鮮時令水果及急凍海產 客人可以安坐家享受日本味道既幸福 公司屋企party 大量優質食品供應 開張節日時令果籃為你度身訂造送到你客人手上',
      title: '好新鮮APP',
      url: 'http://onelink.to/3nqphw',
    });
  }

  renderUserDetailList(data, index) {
    return (
      <TouchableOpacity
        onPress={() => this.userDataClickAction(index)}
        style={{
          flexDirection: 'row',
          height: 40,
          width: width - 40,
          borderBottomColor: colors.lineColor,
          borderBottomWidth: 1,
        }}>
        <View
          style={{
            flex: data.width1,
            alignItems: 'center',
            flexDirection: 'row',
          }}>
          <Icon
            style={{ marginLeft: 10 }}
            color={colors.mainColor}
            name={data.icon}
            size={25}
          />
          <Text style={styles.textStyle}>
            {this.titleStringReturn(data.title)}
          </Text>
        </View>
        <View
          style={{
            flex: data.width2,
            justifyContent: 'center',
            alignItems: 'flex-end',
          }}>
          <Text
            style={{
              color: colors.inputText,
              marginRight: 10,
              fontWeight: 'bold',
            }}>
            {this.contentReturn(index, data)}
          </Text>
        </View>
      </TouchableOpacity>
    );
  }

  contentReturn(index, data) {
    // if (index == 4) {
    //   return this.addressReturn();
    // } else if (index == 3) {
    //   return this.store.points;
    // } else {
    //   return data.content;
    // }
    switch (index) {
      case 0:
        if (this.store.loginUserData.data.display_name == '') {
          return this.store.text.clickHereToEnterYourName;
        } else {
          return this.store.loginUserData.data.display_name;
        }
        break;

      case 1:
        return this.store.loginUserData.data.email;
        break;
      case 2:
        if (this.store.loginUserData.data.country_code == null) {
          return this.store.text.clickHereToEnterYourMobile;
        } else {
          return (
            this.store.loginUserData.data.country_code +
            ' ' +
            this.store.loginUserData.data.mobile
          );
        }

        break;
      case 3:
        return this.store.points;
        break;
      case 4:
        return this.addressReturn();
        break;
    }
  }

  render() {
    return (
      <MenuProvider
        style={{
          flex: 1,
          backgroundColor: colors.bgc,
        }}>
        <Loading loading={this.store.loading} />
        <TitleBar showBack={true} title={this.store.text.setting} self={this} />
        <ScrollView>
          <View style={{ marginLeft: 20, marginRight: 20 }}>
            <Menu
              name="lang"
              renderer={SlideInMenu}
              onSelect={value => {
                this.selectLangAction(value);
              }}>
              <MenuTrigger
                //disabled={!this.editable}
                style={{ flexDirection: 'row', marginBottom: 5 }}
                style={styles.lineSytle}>
                <View style={{ flex: 0.5, justifyContent: 'center' }}>
                  <Text style={styles.textStyle}>
                    {this.store.text.language}
                  </Text>
                </View>
                <View
                  style={{
                    flex: 0.5,
                    justifyContent: 'center',
                    alignItems: 'flex-end',
                  }}>
                  <Text
                    style={{
                      color: colors.mainColor,
                      marginRight: 10,
                      fontWeight: 'bold',
                    }}>
                    {this.lang}
                  </Text>
                </View>
              </MenuTrigger>
              <MenuOptions
                customStyles={{
                  optionText: {
                    margin: 5,
                    color: 'white',
                    fontSize: 15,
                  },
                  optionWrapper: {
                    backgroundColor: colors.mainColor,
                    alignItems: 'center',
                  },
                }}>
                {langList.map((obj, i) => {
                  return <MenuOption value={obj} text={obj.label} />;
                })}
              </MenuOptions>
            </Menu>

            <View style={styles.lineSytle}>
              <View style={{ flex: 0.5, justifyContent: 'center' }}>
                <Text style={styles.textStyle}>
                  {this.store.text.notification}
                </Text>
              </View>
              <View
                style={{
                  flex: 0.5,
                  justifyContent: 'center',
                  alignItems: 'flex-end',
                }}>
                <Switch
                  value={this.notification}
                  backgroundActive={colors.mainColor}
                  onSyncPress={value => {
                    (this.notification = value),
                      console.log(value + '   ' + this.notification);
                  }}
                />
              </View>
            </View>
            <TouchableOpacity style={styles.lineSytle}
              onPress={() => {
                Linking.canOpenURL('https://puremall.com.hk/tnc.html').then(
                  supported => {
                    if (supported) {
                      Linking.openURL('https://puremall.com.hk/tnc.html');
                    } else {
                      console.log(
                        "Don't know how to open URI: " +
                        response.data.wechat.qr_code_url,
                      );
                    }
                  })
              }}>
              <View style={{ flex: 0.5, justifyContent: 'center' }}>
                <Text style={styles.textStyle}>
                  {this.store.text.tearmsOfService}
                </Text>
              </View>
              <View
                style={{
                  flex: 0.5,
                  justifyContent: 'center',
                  alignItems: 'flex-end',
                }}>
                <Icon name="chevron-right" size={35} />
              </View>
            </TouchableOpacity>
            <TouchableOpacity style={styles.lineSytle}
              onPress={() => {
                Linking.canOpenURL('https://puremall.com.hk/privacy.html').then(
                  supported => {
                    if (supported) {
                      Linking.openURL('https://puremall.com.hk/privacy.html');
                    } else {
                      console.log(
                        "Don't know how to open URI: " +
                        response.data.wechat.qr_code_url,
                      );
                    }
                  })
              }}>
              <View style={{ flex: 0.5, justifyContent: 'center' }}>
                <Text style={styles.textStyle}>
                  {this.store.text.privacyPolicy}
                </Text>
              </View>
              <View
                style={{
                  flex: 0.5,
                  justifyContent: 'center',
                  alignItems: 'flex-end',
                }}>
                <Icon name="chevron-right" size={35} />
              </View>
            </TouchableOpacity>
            <TouchableOpacity style={styles.lineSytle}
              onPress={() => {
                this.props.navigation.navigate('Tutorial')
              }}>
              <View style={{ flex: 0.5, justifyContent: 'center' }}>
                <Text style={styles.textStyle}>
                  {this.store.text.tutorial}
                </Text>
              </View>
              <View
                style={{
                  flex: 0.5,
                  justifyContent: 'center',
                  alignItems: 'flex-end',
                }}>
                <Icon name="chevron-right" size={35} />
              </View>
            </TouchableOpacity>
            <TouchableOpacity style={styles.lineSytle}
              onPress={() => {
                this.introVisable = true
              }}>
              <View style={{ flex: 0.5, justifyContent: 'center' }}>
                <Text style={styles.textStyle}>
                  {this.store.text.shopppingGroupIntroduction}
                </Text>
              </View>
              <View
                style={{
                  flex: 0.5,
                  justifyContent: 'center',
                  alignItems: 'flex-end',
                }}>
                <Icon name="chevron-right" size={35} />
              </View>
            </TouchableOpacity>

            {this.store.loginUserData.data.mobile != null ? (<TouchableOpacity style={styles.lineSytle}
              onPress={() => {
                console.log('forgotPW')
                if (this.store.loginUserData.data.mobile != null) {
                  this.props.navigation.navigate('ForgotPassword');
                } else {
                  Alert.alert('', '請先加入電話號碼', [
                    { text: '取消', onPress: () => console.log('Cancel') },
                    {
                      text: '加入',
                      onPress: () => {
                        this.props.navigation.navigate('SignUpVerify', {
                          data: {
                            first_name: '',
                            last_name: '',
                            welcome_code: '',
                            country_code: '+852',
                            mobile: '',
                            email: '',
                            ver_code: '',
                            password: '',
                          },
                          addMobile: true,
                        });
                      },
                    },
                  ]);
                }
              }}>
              <View
                style={{ flex: 0.5, justifyContent: 'center' }}
              >
                <Text style={styles.textStyle}>
                  {this.store.text.forgotPassword}
                </Text>
              </View>
              <View
                style={{
                  flex: 0.5,
                  justifyContent: 'center',
                  alignItems: 'flex-end',
                }}>
                <Icon name="chevron-right" size={35} />
              </View>
            </TouchableOpacity>) : (<TouchableOpacity style={styles.lineSytle}
              onPress={() => {
                this.props.navigation.navigate('SignUpVerify', {
                  data: {
                    first_name: '',
                    last_name: '',
                    welcome_code: '',
                    country_code: '+852',
                    mobile: '',
                    email: '',
                    ver_code: '',
                    password: '',
                  },
                  addMobile: true,
                });
              }}>
              <View
                style={{ flex: 0.5, justifyContent: 'center' }}

              >
                <Text style={styles.textStyle}>
                  {this.store.text.addMobile}
                </Text>
              </View>
              <View
                style={{
                  flex: 0.5,
                  justifyContent: 'center',
                  alignItems: 'flex-end',
                }}>
                <Icon name="chevron-right" size={35} />
              </View>
            </TouchableOpacity>)}
            <TouchableOpacity style={styles.lineSytle}
              onPress={() => {
                this.store.logoutPost(this);
              }}>
              <View
                style={{ flex: 0.5, justifyContent: 'center' }}
              >
                <Text style={styles.textStyle}>{this.store.text.logout}</Text>
              </View>
              <View
                style={{
                  flex: 0.5,
                  justifyContent: 'center',
                  alignItems: 'flex-end',
                }}>
                <Icon name="chevron-right" size={35} />
              </View>
            </TouchableOpacity>
          </View>
          <View
            style={{
              width: width,
              alignItems: 'center',
              marginTop: 20,
              marginBottom: 20,
            }}>
            {/* <CustomLoginButton
              title="Logout"
              color={colors.profileBg}
              textColor={colors.inputText}
              onPress={() => {
                this.store.logoutPost(this);
              }}
            /> */}
          </View>
        </ScrollView>
        <Modal isVisible={this.introVisable}
          deviceWidth={width}
          deviceHeight={height}>
          <View style={{ height: height * 0.8, backgroundColor: 'white', borderRadius: 20 }}>
            {/* <Text style = {{margin:20}}>
                {this.store.text.shoppingGroup}
              </Text> */}
            <View style={{ height: 50, alignItems: 'flex-end', justifyContent: 'center', }}>
              <TouchableOpacity style={{ marginRight: 20 }} onPress={() => this.introVisable = false}>
                <Icon name='close' color={colors.mainColor} size={30} />
              </TouchableOpacity>

            </View>
            <ScrollView style={{ margin: 20 }}>


              <HTMLView
                value={this.store.shoppingGroupIntro}

                addLineBreaks={false}
                paragraphBreak={false}
                //stylesheet={{ fontSize: 10, marginTop: 0, fontSize: 14 ,}}
                stylesheet={{

                  marginTop: 40,
                  br: { marginTop: -25, fontSize: 18 },
                  p: { marginTop: 0, fontSize: 15 }
                }}
              />

            </ScrollView>

          </View>
        </Modal>

      </MenuProvider>
    );
  }
}

const styles = StyleSheet.create({
  lineSytle: {
    flexDirection: 'row',
    height: 60,
    width: width - 40,
    borderBottomColor: colors.lineColor,
    borderBottomWidth: 1,
  },
  textStyle: {
    fontWeight: '800',
    fontSize: 15,
    marginLeft: 10,
  },
});
