import React from 'react';
import {
  SafeAreaView,
  Text,
  View,
  TouchableOpacity,
  Image,
  Keyboard,
  Platform,
  TouchableWithoutFeedback,
} from 'react-native';
import { inject, observer } from "mobx-react"
import { observable, makeObservable } from 'mobx'
// import { GoogleSignin, statusCodes } from '@react-native-community/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 GoogleIcon from 'react-native-vector-icons/dist/MaterialCommunityIcons'
import CustomTextInput from '../../components/customTextInput';
import CustomLoginButton from '../../components/customLoginButton';
// import {
//   AccessToken,
//   GraphRequest,
//   GraphRequestManager,
//   LoginManager,
// } from 'react-native-fbsdk';
// import appleAuth, {
//   AppleButton,
//   AppleAuthRequestOperation,
//   AppleAuthRequestScope,
// } from '@invertase/react-native-apple-authentication';
import { thisExpression } from '@babel/types';

Icon.loadFont();
const Signin = inject("appStore")(observer(class Signin extends React.Component {

  loginUserData = {
    username: '',
    password: '',
  };

  constructor(props) {
    super(props);
    this.store = props.appStore;
    makeObservable(this, {
      loginUserData: observable,
    })
  }

  loginAction() {
    if (this.loginUserData.username !== '') {
      if (this.loginUserData.password !== '') {
        this.store.loginPost(this, this.loginUserData, 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:
    //     '793368908269-qkaqbmik1pbs1540n82fkog0sea8a7rb.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 handleResponse() {
    // try {
    //   // performs login request
    //   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) {
    //   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
        style={{
          backgroundColor: 'white',
          height: 50,
          borderRadius: 30,
          width: width - 40,
          justifyContent: 'center',
          alignItems: 'center',
          marginTop: 20,
        }}
        onPress={() => {
          if (name == 'google') {
            console.log('google');
            this.loginWithGoogle();
          } else {
            this.loginWithFacebook();
          }
        }}>
        {name === 'facebook' ? (
          <Image
            style={{ position: 'absolute', left: 20 }}
            source={images.signIn.facebook}
          />
        ) : (
          <Image
            style={{ position: 'absolute', left: 20 }}
            source={images.signIn.google}
          />
        )}
        <Text style={{ fontWeight: 'bold', color: colors.titleColor }}>
          {name === 'facebook'
            ? 'Sign in with Facebook'
            : 'Sign in with Google'}
        </Text>
      </TouchableOpacity>
    );
  }
  render() {
    return (
      <TouchableWithoutFeedback onPress={Keyboard.dismiss} accessible={false}>
        <SafeAreaView
          style={{
            flex: 1,
          }}>
          <View
            style={{
              flex: 0.1,
              backgroundColor: colors.mainColor,
              justifyContent: 'center',
            }}>
            <TouchableOpacity
              style={{
                height: 60,
                width: 60,
                justifyContent: 'center',
                alignItems: 'center',
              }}
              onPress={() => {
                this.props.navigation.goBack();
              }}>
              <GoogleIcon name="chevron-left" color="white" size={40} />
            </TouchableOpacity>
          </View>
          <View
            style={{
              flex: 0.45,
              backgroundColor: colors.mainColor,
              justifyContent: 'center',
              alignItems: 'center',
            }}>
            <CustomTextInput
              title={this.store.text.email}
              value={this.loginUserData.username}
              onChangeText={text => {
                this.loginUserData.username = text;
              }}
              returnKeyType={'next'}
              secureTextEntry={false}
              onSubmitEditing={event => {
                this.passwordinput.focus();
              }}
            />
            <CustomTextInput
              title={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();
              }}
            />
            <CustomLoginButton
              title={this.store.text.login}
              onPress={() => {
                this.loginAction();
              }}
            />
            <View style={{ width: width, marginTop: 10 }}>
              <TouchableOpacity
                style={{
                  marginLeft: 20,
                  height: 30,
                  width: 100,
                  justifyContent: 'center',
                  alignItems: 'center',
                }}
                onPress={() => {
                  this.props.navigation.navigate('ForgotPassword');
                }}>
                <Text style={{ fontSize: 10 }}>
                  {this.store.text.forgotPassword + '?'}
                </Text>
              </TouchableOpacity>
            </View>
          </View>
          <View
            style={{
              flex: 0.45,
              backgroundColor: colors.otherGreen,
              justifyContent: 'center',
              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,
              }}
            /> */}
            <TouchableOpacity
              style={{
                height: 30,
                width: 200,
                marginTop: 5,
                justifyContent: 'center',
                alignItems: 'center',
              }}
              onPress={() => {
                this.props.navigation.navigate('Signup');
              }}>
              <Text style={{ fontSize: 12, color: 'white', fontWeight: 'bold' }}>
                {this.store.text.noAcountSignUp}
              </Text>
            </TouchableOpacity>
            <View style={{ width: width, alignItems: 'flex-end' }}>
              <Image
                style={{ marginRight: 10 }}
                source={images.signIn.illustration}
              />
            </View>
          </View>
          <Toast
            ref="toast"
            style={{ backgroundColor: colors.mainColor }}
            position="center"
            positionValue={200}
            fadeInDuration={750}
            fadeOutDuration={2000}
            opacity={0.8}
            textStyle={{ color: 'white' }}
          />
        </SafeAreaView>
      </TouchableWithoutFeedback>
    );
  }
}))
export default Signin
