import React from 'react';
import {
  SafeAreaView,
  Text,
  View,
  TouchableOpacity,
  Image,
  Keyboard,
  Platform,
  TouchableWithoutFeedback,
  ImageBackground,
  ScrollView,
} from 'react-native';
import { inject, observer } from 'mobx-react';
import { observable } from 'mobx';
import FastImage from 'react-native-fast-image'
import { Input } from 'react-native-elements';
import { Hoshi } from 'react-native-textinput-effects';
import TitleBar from '../../components/titleBar';
import { GoogleSignin, statusCodes } from '@react-native-google-signin/google-signin';
import { images } from '../../assets/images/imageIndex';
import Toast, { DURATION } from 'react-native-easy-toast';
import { width, height } from '../../services/screen';
import { colors } from '../../assets/styles/colors-theme';
import Icon from 'react-native-vector-icons/dist/Ionicons';
import FontAwsome from 'react-native-vector-icons/FontAwesome';
import CustomTextInput from '../../components/customTextInput';
import HoshiTextInput from '../../components/hoshiTextInput';
import CustomLoginButton from '../../components/customLoginButton';
import { getStatusBarHeight } from 'react-native-status-bar-height';
// import {
//   AccessToken,
//   GraphRequest,
//   GraphRequestManager,
//   LoginManager,
// } from 'react-native-fbsdk';
import appleAuth, {
  AppleButton,
  AppleAuthRequestOperation,
  AppleAuthRequestScope,
} from '@invertase/react-native-apple-authentication';


Icon.loadFont();
FontAwsome.loadFont();
@inject('appStore')
@observer
export default class Signin extends React.Component {
  @observable
  loginUserData = {
    username: '',
    password: '',
  };

  constructor(props) {
    super(props);
    this.store = props.appStore;

  }

  isNumeric(value) {
    return /^\d+$/.test(value);
  }

  loginAction() {
    if (this.loginUserData.username !== '') {
      if (this.loginUserData.password !== '') {
        if (this.isNumeric(this.loginUserData.username)) {
          this.loginUserData.username = this.loginUserData.username.slice(0, 0) + '852' + this.loginUserData.username.slice(0);
        }
        var loginData = {
          email: this.loginUserData.username,
          pwd: this.loginUserData.password
        }
        this.store.loginPost(this, loginData, true);
      } else {
        this.refs.toast.show(this.store.text.pleaseInputYourPassword);
      }
    } else {
      this.refs.toast.show(this.store.text.pleaseInputYourEmail);
    }
  }

  componentDidMount() {
    this._configureGoogleSignIn();
  }

  _configureGoogleSignIn() {
    GoogleSignin.configure({
      webClientId:
        '966559802795-nogv7cmugqkk4ocuev818u5hicpnrhaf.apps.googleusercontent.com',
      offlineAccess: false,
    });
  }

  async loginWithGoogle() {
    try {
      await GoogleSignin.hasPlayServices();
      const userInfo = await GoogleSignin.signIn();
      console.log(userInfo.idToken);
      const isSignedIn = await GoogleSignin.getTokens();
      var data = {
        platform: 'google',
        token: isSignedIn.accessToken,
      };
      this.store.thirdPartyLogin(data, this, false);
      console.log(isSignedIn);
    } catch (error) {
      console.log(error);
      if (error.code === statusCodes.SIGN_IN_CANCELLED) {
        // user cancelled the login flow
      } else if (error.code === statusCodes.IN_PROGRESS) {
        // operation (e.g. sign in) is in progress already
      } else if (error.code === statusCodes.PLAY_SERVICES_NOT_AVAILABLE) {
        // play services not available or outdated
      } else {
        // some other error happened
      }
    }
  }
  async onAppleButtonPress() {

    const appleAuthRequestResponse = await appleAuth.performRequest({
      requestedOperation: appleAuth.Operation.LOGIN,
      requestedScopes: [appleAuth.Scope.EMAIL, appleAuth.Scope.FULL_NAME],
    });
    // get current authentication state for user
    // /!\ This method must be tested on a real device. On the iOS simulator it always throws an error.
    const credentialState = await appleAuth.getCredentialStateForUser(
      appleAuthRequestResponse.user,
    );
    // use credentialState response to ensure the user is authenticated
    if (credentialState === appleAuth.State.AUTHORIZED) {
      this.store.loginWithApple(
        appleAuthRequestResponse.identityToken,
        this,
        false,
      );
      // user is authenticated
    }
  }

  async handleResponse() {
    try {

      const appleAuthRequestResponse = await appleAuth.performRequest({
        requestedOperation: AppleAuthRequestOperation.LOGIN,
        requestedScopes: [
          AppleAuthRequestScope.EMAIL,
          AppleAuthRequestScope.FULL_NAME,
        ],
      });
      if (appleAuthRequestResponse['realUserStatus']) {
        console.log(appleAuthRequestResponse);
        this.store.loginWithApple(
          appleAuthRequestResponse.identityToken,
          this,
          false,
        );
      }
    } catch (error) {
      console.log(error);
      // if (error.code === AppleAuthError.CANCELED) {
      // }
      // if (error.code === AppleAuthError.FAILED) {
      //   alert('Touch ID wrong');
      // }
      // if (error.code === AppleAuthError.INVALID_RESPONSE) {
      //   alert('Touch ID wrong');
      // }
      // if (error.code === AppleAuthError.NOT_HANDLED) {
      // }
      // if (error.code === AppleAuthError.UNKNOWN) {
      //   alert('Touch ID wrong');
      // }
    }
  }

  loginWithFacebook() {
    // Attempt a login using the Facebook login dialog asking for default permissions.
    // LoginManager.logInWithPermissions(['public_profile', 'email']).then(
    //   login => {
    //     if (login.isCancelled) {
    //       console.log('Login cancelled');
    //     } else {
    //       AccessToken.getCurrentAccessToken().then(data => {
    //         const accessToken = data.accessToken.toString();
    //         data = {
    //           platform: 'facebook',
    //           token: accessToken,
    //         };
    //         this.store.loading = false;
    //         this.store.thirdPartyLogin(data, this, false);
    //         // this.store.thirdPartyLogin(
    //         //   data,
    //         //   this,
    //         //   !this.props.navigation.state.params.icon,
    //         // );
    //         //  Alert.alert( JSON.stringify(accessToken))
    //         console.log(accessToken);
    //         //  this.getInfoFromToken(accessToken);
    //       });
    //     }
    //   },
    //   error => {
    //     console.log('Login fail with error: ' + JSON.stringify(error));
    //     Alert.alert('fblogin', JSON.stringify(error));
    //   },
    // );
  }

  renderThirdPartyLogin(name) {
    return (
      <TouchableOpacity
        onPress={() => {
          if (name == 'google') {
            console.log('google');
            this.loginWithGoogle();
          } else {
            this.loginWithFacebook();
          }
        }}
        style={{
          borderColor: name === 'facebook' ? '#3E5C9A' : '#DF4B39',
          height: 50,
          borderWidth: 1,
          borderRadius: 30,
          width: width - 60,
          justifyContent: 'center',
          alignItems: 'center',
          marginTop: 10,
          flexDirection: 'row',
        }}>
        <View
          style={{
            flex: 0.3,
            justifyContent: 'center',
            alignItems: 'flex-end',
          }}>
          <FontAwsome
            name={name === 'facebook' ? 'facebook' : 'google'}
            color={name === 'facebook' ? '#3E5C9A' : '#DF4B39'}
            size={15}
          />
        </View>
        <View
          style={{
            flex: 0.4,
            justifyContent: 'center',
            alignItems: 'center',
          }}>
          <Text
            style={{
              color: name === 'facebook' ? '#3E5C9A' : '#DF4B39',
              fontSize: 16,
            }}>
            {name === 'facebook'
              ? 'Facebook' + this.store.text.login
              : 'Google' + this.store.text.login}
          </Text>
        </View>
        <View
          style={{
            flex: 0.3,
            justifyContent: 'center',
            alignItems: 'center',
          }}
        />
      </TouchableOpacity>
    );
  }
  render() {
    return (
      <TouchableWithoutFeedback onPress={Keyboard.dismiss} accessible={false}>
        <View
          style={{
            backgroundColor: 'white',
            flex: 1,
            marginTop: Platform.OS === 'ios' ? 0 : getStatusBarHeight(),
          }}>
          <TitleBar showBack={true} self={this} />
          {/* <View
            style={{
              justifyContent: 'center',
            }}>
            <TouchableOpacity
              style={{
                height: 60,
                width: 60,
                justifyContent: 'center',
                alignItems: 'center',
              }}
              onPress={() => {
                this.props.navigation.goBack();
              }}>
              <Icon name="ios-arrow-back" color={'black'} size={40} />
            </TouchableOpacity>
          </View> */}
          <View
            style={{
              flex: 0.2,
              justifyContent: 'center',
              alignItems: 'center',
            }}>
            <Image source={images.signIn.logo} />
          </View>
          <View
            style={{
              flex: 0.8,

              alignItems: 'center',
            }}>

            {/* {this.renderThirdPartyLogin('google')}
            {this.renderThirdPartyLogin('facebook')}
            {Platform.OS === 'ios' ? (
              <TouchableOpacity
                style={{
                  backgroundColor: 'white',
                  height: 50,
                  borderRadius: 30,
                  width: width - 40,
                  justifyContent: 'center',
                  alignItems: 'center',
                  marginTop: 20,
                }}
                onPress={() => {
                  this.handleResponse();
                }}>
                <Icon
                  style={{position: 'absolute', left: 20}}
                  name="logo-apple"
                  size={40}
                />

                <Text style={{fontWeight: 'bold', color: 'black'}}>
                  Sign in with Apple
                </Text>
              </TouchableOpacity>
            ) : (
              <View />
            )} */}

            {/* <AppleButton
              buttonStyle={AppleButton.Style.BLACK}
              buttonType={AppleButton.Type.SIGN_IN}
              onPress={() => this.handleResponse()}
              style={{
                width: 300,
                height: 50,
                margin: 10,
              }}
            /> */}
            <ScrollView>
              <View style={{ width: width, alignItems: 'center' }}>


                <HoshiTextInput
                  placeholder={this.store.text.emailorphone}
                  value={this.loginUserData.username}
                  onChangeText={text => {
                    this.loginUserData.username = text;
                  }}
                  returnKeyType={'next'}
                  secureTextEntry={false}
                  onSubmitEditing={event => {
                    this.passwordinput.focus();
                  }}
                />
                <HoshiTextInput
                  password={true}
                  placeholder={this.store.text.password}
                  value={this.loginUserData.password}
                  onChangeText={text => {
                    this.loginUserData.password = text;
                  }}
                  secureTextEntry={true}
                  returnKeyType={'done'}
                  inputRef={input => {
                    this.passwordinput = input;
                  }}
                  onSubmitEditing={event => {
                    Keyboard.dismiss();
                  }}
                />
                <View
                  style={{
                    width: width,
                    margin: 20,
                    justifyContent: 'center',
                    alignItems: 'flex-end',
                  }}>
                  <TouchableOpacity
                    style={{
                      marginRight: 25,
                      marginTop: 10,
                      height: 30,
                      width: 100,
                      justifyContent: 'center',
                      alignItems: 'flex-end',
                    }}
                    onPress={() => {
                      this.props.navigation.navigate('ForgotPassword');
                    }}>
                    <Text style={{ fontSize: 13 }}>
                      {this.store.text.forgotPassword + '?'}
                    </Text>
                  </TouchableOpacity>
                </View>

                <CustomLoginButton
                  title={this.store.text.login}
                  onPress={() => {
                    this.loginAction();
                  }}
                />
                <View style={{ marginTop: 20 }} />
                {/* {this.renderThirdPartyLogin('facebook')} */}

                {this.renderThirdPartyLogin('google')}


                {Platform.OS == 'ios' ? (
                  <View
                    style={{
                      width: width,
                      justifyContent: 'center',
                      alignItems: 'center',

                    }}>
                    {/* <AppleButton
                    buttonStyle={AppleButton.Style.BLACK}
                    buttonType={AppleButton.Type.SIGN_IN}
                    style={{
                      width: width - 120, // You must specify a width
                      height: 40, // You must specify a height
                    }}
                    onPress={() => {
                      this.onAppleButtonPress();
                    }}
                  /> */}

                    <TouchableOpacity
                      onPress={() => {
                        this.onAppleButtonPress();
                      }}
                      style={{
                        borderColor: 'black',
                        height: 50,
                        borderWidth: 1,
                        borderRadius: 30,
                        width: width - 60,
                        justifyContent: 'center',
                        alignItems: 'center',
                        marginTop: 10,
                        flexDirection: 'row',
                      }}>
                      <View
                        style={{
                          flex: 0.3,
                          justifyContent: 'center',
                          alignItems: 'flex-end',
                        }}>
                        <FontAwsome
                          name={'apple'}

                          size={15}
                        />
                      </View>
                      <View
                        style={{
                          flex: 0.4,
                          justifyContent: 'center',
                          alignItems: 'center',
                        }}>
                        <Text
                          style={{

                            fontSize: 16,
                          }}>
                          {'Sign in with Apple'}
                        </Text>
                      </View>
                      <View
                        style={{
                          flex: 0.3,
                          justifyContent: 'center',
                          alignItems: 'center',
                        }}
                      />
                    </TouchableOpacity>

                  </View>
                ) : (
                    <View />
                  )}

                <TouchableOpacity
                  style={{
                    height: 30,
                    width: 200,
                    marginTop: 5,
                    justifyContent: 'center',
                    alignItems: 'center',
                  }}
                  onPress={() => {
                    this.props.navigation.navigate('Signup');
                  }}>
                  <Text
                    style={{
                      fontSize: 14,
                      color: 'black',
                      fontWeight: 'bold',
                    }}>
                    {this.store.text.noAcountSignUp}
                  </Text>
                </TouchableOpacity>
              </View>
            </ScrollView>
          </View>
          <Toast
            ref="toast"
            style={{ backgroundColor: colors.mainColor }}
            position="center"
            positionValue={200}
            fadeInDuration={750}
            fadeOutDuration={2000}
            opacity={0.8}
            textStyle={{ color: 'white' }}
          />
        </View>
      </TouchableWithoutFeedback>
    );
  }
}
