import React from 'react';
import {
  SafeAreaView,
  Text,
  View,
  TouchableOpacity,
  StyleSheet,
  Image,
  ScrollView,
  Share,
  Alert,
} from 'react-native';
var _ = require('lodash');
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 { observable, makeObservable } from 'mobx'
import { colors } from '../../assets/styles/colors-theme';
import Rank from '../../components/rank';
import TitleBar from '../../components/titleBar';
import CustomLoginButton from '../../components/customLoginButton';
import { getStatusBarHeight } from 'react-native-status-bar-height';
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' },
];
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();
const Profile = inject("appStore")(observer(class Profile extends React.Component {
  notification = true;
  lang = '中文';
  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;
    makeObservable(this, {
      notification: observable,
      lang: observable,
      data: observable,
    })
    // 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 {
          this.lang = 'English';
        }
      } 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:
        '歌莉生活館專為各位搜羅健康的天然食材、優質牛扒等。我們為你提供合理價錢、高質選擇的低糖低碳、生酮食品。同時我們會提供生酮飲食資訊、並設有生活雜貨。',
      title: '歌莉生活館',
      url: 'http://onelink.to/calihealthylife',
    });
  }

  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={{ color: colors.mainColor, marginLeft: 10 }}>
            {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} />
        <View
          style={{
            height: Platform.OS === 'ios' ? 45 : 70,
            marginTop: Platform.OS === 'ios' ? 0 : getStatusBarHeight(),
            width: width,
            justifyContent: 'center',
            alignItems: 'center',
            backgroundColor: colors.mainColor,
          }}>
          <Text style={{ color: 'white', fontSize: 18, fontWeight: '800' }}>
            {this.store.text.personalFile}
          </Text>
        </View>
        <ScrollView>
          {/* <View
          style={{
            height: 40,
            width: width,
            justifyContent: 'center',
            alignItems: 'center',
            backgroundColor: colors.otherGreen,
          }}>
          <Text style={{color: 'white', fontSize: 15}}>
            {this.store.text.contactInformation}
          </Text>
        </View> */}
          {/* <View
            style={{
              width: width,
              height: 200,
              backgroundColor: '#6EB7A0',
              justifyContent: 'center',
              alignItems: 'center',
              flexDirection: 'row',
            }}>
            <View
              style={{
                height: 150,
                width: 150,
                borderRadius: 150,
                backgroundColor: colors.signupInputBgc,
                justifyContent: 'center',
                alignItems: 'center',
              }}>
              <FontAwesomeIcon
                name="user-o"
                size={80}
                color={colors.profileBg}
              />
              <Text
                style={{color: colors.profileBg, fontSize: 12, marginTop: 10}}>
                Profile Picture
              </Text>
            </View>
          </View> */}
          <View style={{ width: width, backgroundColor: colors.signupInputBgc }}>
            <View
              style={{
                marginLeft: 20,
                marginRight: 20,
                backgroundColor: colors.signupInputBgc,
              }}>
              {this.data.map((items, index) => {
                return this.renderUserDetailList(items, index);
              })}
            </View>
          </View>
          <View
            style={{
              height: 60,
              width: width,
              backgroundColor: 'bgc',
              justifyContent: 'center',
            }}>
            <Text
              style={{
                color: colors.mainColor,
                fontSize: 20,
                fontWeight: '800',
                marginLeft: 30,
              }}>
              {this.store.text.setting}
            </Text>
          </View>
          <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={{
                  flexDirection: 'row',
                  height: 40,
                  width: width - 40,
                  borderBottomColor: colors.lineColor,
                  borderBottomWidth: 1,
                }}>
                <View style={{ flex: 0.5, justifyContent: 'center' }}>
                  <Text style={{ color: colors.mainColor, marginLeft: 10 }}>
                    {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={{
                flexDirection: 'row',
                height: 40,
                width: width - 40,
                borderBottomColor: colors.lineColor,
                borderBottomWidth: 1,
              }}>
              <View style={{ flex: 0.5, justifyContent: 'center' }}>
                <Text style={{ color: colors.mainColor, marginLeft: 10 }}>
                  {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
              onPress={() => this.props.navigation.navigate('CreditCard')}
              style={{
                flexDirection: 'row',
                height: 40,
                width: width - 40,
                borderBottomColor: colors.lineColor,
                borderBottomWidth: 1,
              }}>
              <View style={{ flex: 0.5, justifyContent: 'center' }}>
                <Text style={{ color: colors.mainColor, marginLeft: 10 }}>
                  {this.store.text.creditCardInfo}
                </Text>
              </View>
              <View
                style={{
                  flex: 0.5,
                  justifyContent: 'center',
                  alignItems: 'flex-end',
                }}>
                {/* <Image source={images.profile.creditCardIcon} tintColor = {colors.mainColor}/> */}
                <Icon
                  name="credit-card-multiple"
                  color={colors.mainColor}
                  size={35}
                />
              </View>
            </TouchableOpacity>
            <View
              style={{
                flexDirection: 'row',
                height: 40,
                width: width - 40,
                borderBottomColor: colors.lineColor,
                borderBottomWidth: 1,
              }}>
              <TouchableOpacity
                onPress={() => {
                  this.share();
                }}
                style={{ flex: 0.5, justifyContent: 'center' }}>
                <Text style={{ color: colors.mainColor, marginLeft: 10 }}>
                  {this.store.text.share}
                </Text>
              </TouchableOpacity>
              <View
                style={{
                  flex: 0.5,
                  justifyContent: 'center',
                  alignItems: 'flex-end',
                }}>
                <Image
                  source={images.profile.profileShare}
                  tintColor={colors.mainColor}
                />
              </View>
            </View>
            <TouchableOpacity
              style={{ marginTop: 10 }}
              onPress={() => {
                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,
                        });
                      },
                    },
                  ]);
                }
              }}>
              <Text style={{ marginLeft: 10, fontSize: 11 }}>
                {this.store.text.forgotPassword}
              </Text>
            </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);
              }}
            />
            {/* 
          <TouchableOpacity
            onPress={() => {
              Adyen.startPayment();
            }}
            style={{
              width: 200,
              height: 100,
              justifyContent: 'center',
              alignItems: 'center',
              backgroundColor: colors.mainColor,
            }}>
            <Text style={{color: 'white'}}>Test pay</Text>
          </TouchableOpacity>
          */}
          </View>
        </ScrollView>
      </MenuProvider>
    );
  }
}))
export default Profile
