import React, {Component} from 'react';
import {
     Alert,
     Animated,
     AsyncStorage,
     BackHandler,
     Image,
     PermissionsAndroid,
     Platform,
     ScrollView,
     StatusBar,
     StyleSheet,
     Text,
     TouchableOpacity,
     View
} from 'react-native';
import PropTypes from 'prop-types';
import FontAwesomeIcon from 'react-native-vector-icons/FontAwesome';
import {responsiveFontSize, responsiveHeight, responsiveWidth} from 'react-native-responsive-dimensions';
import {Sae} from 'react-native-textinput-effects';
import Button from 'apsl-react-native-button';
import {getCountryNetwork, login, saveNewuser} from './../../../webservice/AuthApi';
import * as Animatable from 'react-native-animatable';
import isEqual from 'lodash/isEqual'
import SwitchSelector from 'react-native-switch-selector'
import I18n from 'react-native-i18n'
import {IlinkEmitter} from './../../../utils/events'
import {readUser} from "../../../webservice/AuthApi";
import Spinner from "react-native-loading-spinner-overlay";
import Geolocation from "react-native-geolocation-service";
import {callingCodes} from '@ideditor/country-coder';

let theme = require('./../../../utils/theme.json');

let route = require('./../../../route.json');
require('./../../../utils/Translations')
let country = require('./../../../utils/country_code.json');

const GEOLOCATION_OPTIONS = {enableHighAccuracy: true, timeout: 20000}
const propTypes = {
     coordinate: PropTypes.shape({
          latitude: PropTypes.number.isRequired,
          longitude: PropTypes.number.isRequired,
     }),
     children: PropTypes.node,
     geolocationOptions: PropTypes.shape({
          enableHighAccuracy: PropTypes.bool,
          timeout: PropTypes.number,
          maximumAge: PropTypes.number,
     }),
     heading: PropTypes.number,
     enableHack: PropTypes.bool,
};
const widthButton = responsiveWidth(80) > 350 ? 350 : responsiveWidth(80);

export class LoginUi extends Component {

     handlePhoneRef = ref => this.phoneRef = ref;
     handlePasswordRef = ref => this.passRef = ref;
     static defaultProps = {
          enableHack: false,
          geolocationOptions: null,
     };

     async requestCameraPermission() {
          if (Platform.OS === "android") {
               try {
                    const granted = await PermissionsAndroid.request(
                        PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
                        {
                             'title': 'Cool Photo App Camera Permission',
                             'message': 'Cool Photo App needs access to your camera ' +
                                 'so you can take awesome pictures.'
                        }
                    )
                    if (granted === PermissionsAndroid.RESULTS.GRANTED) {
                         this.watchLocation()
                    } else {
                         this.setState({loadingDialog: false})
                         Alert.alert(I18n.t("TITLE_UNABLE_TO_AUTORISE"),
                             I18n.t("MISSING_AUTORISATION_LOCATION"),
                             [{
                                  text: I18n.t("RESTART"), onPress: () => {
                                       this.requestCameraPermission()
                                  }
                             }, {
                                  text: I18n.t("QUIT_"), onPress: () => {
                                       BackHandler.exitApp()
                                  }
                             }],
                             {cancelable: false}
                         )
                    }
               } catch (err) {
                    console.warn(err)
                    this.setState({loadingDialog: false})
                    Alert.alert(I18n.t("TITLE_ERROR_SURVENU"),
                        I18n.t("TEXT_ERROR_START_APPLICATION"),
                        [{
                             text: I18n.t("RESTART"), onPress: () => {
                                  this.requestCameraPermission()
                             }
                        }, {
                             text: I18n.t("QUIT_"), onPress: () => {
                                  // BackHandler.exitApp()
                             }
                        }],
                        {cancelable: false}
                    )

               }
          } else {
               this.watchLocation()

          }
     }

     showConnexionAlertError() {
          this.setState({loadingDialog: false})

          Alert.alert(I18n.t("TITLE_PROBLE_COME"),
              I18n.t("TEXT_UNABLE_TO_GET_YOUR_POSITION"),
              [{
                   text: I18n.t("QUIT_"), onPress: () => {
                        BackHandler.exitApp()
                   }
              }, {
                   text: I18n.t("RESTART"),
                   onPress: () => {
                        this.setState({loadingDialog: true})
                        this.watchLocation()
                   }
              }],
              {cancelable: false}
          )
     }

     _storeData = async (position) => {
          try {
               console.warn("save result", await AsyncStorage.setItem('position', JSON.stringify(position)));
          } catch (error) {
               console.warn("store error", error)
          }
     };
     _retrieveData = async () => {
          try {
               const value = await AsyncStorage.getItem('position');
               if (value !== null) {
                    let re = JSON.parse(value)
                    re.longitudeDelta = 0.04
                    re.latitudeDelta = 0.01
                    const pos = JSON.parse(value)
                    this.setState({region: re, oldPosition: pos})
               }
          } catch (error) {
               console.warn(error)
          }
     };

     watchLocation(geo = null) {
          const options = geo == null ? GEOLOCATION_OPTIONS : geo
          this.watchID = Geolocation.getCurrentPosition((position) => {
                   const myLastPosition = this.state.myPosition;
                   const myPosition = position.coords;
                   if (!isEqual(myPosition, myLastPosition)) {
                        console.warn(myPosition)
                        if (myPosition.longitude !== 0 && myPosition.latitude !== 0) {
                             this._storeData(myPosition)
                             this.retreiveinformationFromPosition(myPosition)
                        } else {
                             if (!this.state.alreadyRetry) {
                                  this.setState({alreadyRetry: true})
                                  let geo = {enableHighAccuracy: false, timeout: 20000, maximumAge: 1000}
                                  this.watchLocation(geo)
                             } else {
                                  if (this.state.oldPosition) {
                                       this.retreiveinformationFromPosition(this.state.oldPosition)
                                  } else {
                                       Geolocation.watchPosition((position) => {
                                            if (position.longitude !== 0 && position.latitude !== 0) {
                                                 this._storeData(position)
                                                 this.retreiveinformationFromPosition(position)
                                            } else {
                                                 Alert.alert(I18n.t("UNABLE_GET_INFORMATION")
                                                     , I18n.t('UNABLE_GET_INFORMATION_TEXT'),
                                                     [{
                                                          text: I18n.t("EXIT"), onPress: () => {
                                                               BackHandler.exitApp()
                                                          }
                                                     },
                                                          {
                                                               text: I18n.t("RESTART"), onPress: () => {
                                                                    this.watchLocation()
                                                               }
                                                          }],
                                                     {cancelable: false}
                                                 )
                                            }
                                       }, (error) => {
                                            this.setState({loadingDialog: false})
                                            Alert.alert(I18n.t("TITLE_ERROR_SURVENU"),
                                                I18n.t("TEXT_ERROR_START_APPLICATION"),
                                                [{
                                                     text: "Ok", onPress: () => {
                                                          BackHandler.exitApp()
                                                     }
                                                }],
                                                {cancelable: false})
                                       }, GEOLOCATION_OPTIONS)
                                  }
                             }
                        }
                   }

              }, (positionError) => {
                   console.warn(positionError)
                   Alert.alert(I18n.t("UNABLE_GET_INFORMATION")
                       , I18n.t('UNABLE_GET_INFORMATION_TEXT'),
                       [{
                            text: I18n.t("EXIT"), onPress: () => {
                                 BackHandler.exitApp()
                            }
                       },
                            {
                                 text: I18n.t("RESTART"), onPress: () => {
                                      this.watchLocation()
                                 }
                            }],
                       {cancelable: false}
                   )
              }
              , options)
     }


     retreiveinformationFromPosition(myPosition) {
          let indicatif = callingCodes([myPosition.longitude, myPosition.latitude]);
          this.setState({
               indicatif: `+${indicatif}`,
               enterPhone: `+${indicatif}`
          });

          /*        getOpenCagePositionInformation(myPosition).then((response) => {
                      console.log("OPENCAGE RESPONSE", response);
                      if (response.results !== undefined) {
                          if (response.results.length > 0) {
                              let most = response.results[0]
                              let {address_components, county, country} = most.components;
                              let indicatif = callingCodes([myPosition.longitude, myPosition.latitude]);
                              console.log("OPENCAGE RESPONSE", indicatif);
                              this.setState({
                                  address: address_components,
                                  textadress: most.formatted,
                                  indicatif: `+${indicatif}`,
                                  enterPhone: `+${indicatif}`,
                                  shortCountry: county,
                                  longCountry: country
                              });
                              //this.getNetworks(country);
                          } else {
                          }
                          this.setState({phoneEnabled: true, loadingDialog: false});

                      } else {
                          console.log(myPosition, response)
                          this.showConnexionAlertError()
                      }
                  }).catch((e) => {
                      console.log("OPENCAGE ERROR", e);
                      this.setState({phoneEnabled: true, loadingDialog: false});
                  });*/
     }

     componentDidMount() {
          this._retrieveData();
          this.requestCameraPermission();

     }

     componentWillUnmount() {
          if (this.focusListener)
               this.focusListener.remove()
     }

     getNetworks(pays) {

          if (pays) {
               getCountryNetwork(pays).then((result) => {
                    this.reseaux = [];
                    let networks = result[0];
                    for (let prop in networks) {
                         if (networks[prop] !== "" && networks[prop].toLowerCase() !== pays.toLowerCase()) {
                              this.reseaux.push(networks[prop]);
                         }
                    }
                    this.setState({networks: this.reseaux});

               }, (err) => {
                    console.log(err);
               });
          } else {
               let msg = "impossible de récupérer le nom du pays";
          }
     }

     constructor(props) {
          super(props);
          this.state = this.initState();
          this.Animation = new Animated.Value(0);
          this.BackgroundColorConfig = this.Animation.interpolate(
              {
                   inputRange: [0, 0.5, 1],
                   outputRange: this.state.colorsscheme
              });
          this.BackgroundColorConfigAdmin = this.Animation.interpolate(
              {
                   inputRange: [0, 0.5, 1],
                   outputRange: this.state.colorsscheme.reverse()
              })

     }

     StartBackgroundColorAnimation = (value) => {
          this.Animation.setValue(value === 0 ? 0 : 1);
          this.setState({stateLogin: value, typeaccount: value})
          Animated.timing(
              this.Animation,
              {
                   toValueF: value === 1 ? 0 : 1,
                   duration: 500
              }
          ).start();
     }

     async gotoHome() {

          IlinkEmitter.emit("userconnect")
          let readU = await readUser()
          let road = "";
          if (!readU.category)
               road = "App"
          else {
               switch (readU.category) {
                    case 'geolocated':
                         road = "AgentApp"
                         break;
                    case 'super':
                         road = "adminApp"
                         break
                    default:
                         road = "supAdminApp"
               }
          }


          this.props.navigation.navigate(road);


     }

     gotoTypeCreated() {
          this.props.navigation.push(route.typeaccountcreate, {
               type: this.state.typeaccount,
          });
     }

     initState() {
          return {
               password: "",
               typeaccount: 0,
               enterPhone: "",
               isLoging: false,
               phoneEnabled: false,
               snackVisible: false,
               snackText: '',
               loadingDialog: false,
               stateLogin: -1,
               colorsscheme: [theme.primary, theme.primaryDark, theme.primaryDarkAdvanced]
          }
     }

     options = [
          {label: I18n.t('USER'), value: 0},
          {label: I18n.t('AGENT'), value: 1},
     ]

     BackgroundColorConfig: null
     BackgroundColorConfigAdmin: null

     render() {

          return (
              <Animated.View style={[style.container,
                   {backgroundColor: this.BackgroundColorConfig}]}>
                   <StatusBar
                       backgroundColor={theme.primaryDark}
                       barStyle="light-content"
                       translucent={false}

                   /><Spinner
                  visible={this.state.loadingDialog}
                  textContent={I18n.t("LOADING_PROGRESS")}
                  textStyle={{color: '#FFF'}}
              />

                   <ScrollView>
                        <TouchableOpacity onPress={() => {

                             this.props.navigation.push(route.helpScreen)

                        }}>
                             <View style={{
                                  alignSelf: 'flex-end',
                                  justifyContent: 'center',
                                  alignItems: 'center',
                                  backgroundColor: theme.primaryLight,
                                  height: 32,
                                  borderRadius: 12,
                                  marginTop: 30,
                                  marginRight: 20
                             }}>
                                  <Text style={{
                                       color: 'white',
                                       fontSize: 18,
                                       fontWeight: 'bold',
                                       padding: 5
                                  }}>{I18n.t('HELP')}</Text>
                             </View>
                        </TouchableOpacity>
                        <View style={style.logoContaner}>
                             <Image style={style.logo} source={require('./../../../datas/img/icon3.png')}/>
                        </View>
                        <Animatable.View ref={this.handlePhoneRef}>
                             <Sae
                                 label={this.state.stateLogin !== 1 ? I18n.t('PHONE_NUMBER') : I18n.t('PHONE_NUMBER_ADMIN')}
                                 iconClass={FontAwesomeIcon}
                                 iconName={'phone'}
                                 iconColor={'white'}
                                 keyboardType={"numeric"}
                                 enabled={this.state.phoneEnabled}
                                 style={style.input}
                                 autoCapitalize={'none'}
                                 autoCorrect={false}
                                 value={this.state.enterPhone}
                                 ref={(com) => {
                                      this.numberRef = com
                                 }}
                                 onChangeText={(text) => this.setState({enterPhone: text})}
                                 labelStyle={style.labelInput}
                             />
                        </Animatable.View>
                        <Animatable.View ref={this.handlePasswordRef}>
                             <Sae
                                 label={I18n.t('PASSWORD')}
                                 ref={component => {
                                      this._pass = component
                                 }}
                                 iconClass={FontAwesomeIcon}
                                 iconName={'lock'}
                                 style={style.input}
                                 iconColor={'white'}
                                 labelStyle={style.labelInput}
                                 autoCapitalize={'none'}
                                 secureTextEntry={true}
                                 onChangeText={(text) => this.setState({password: text})}
                                 autoCorrect={false}
                             />
                        </Animatable.View>


                        <View style={separator.btnContainer}>
                             <TouchableOpacity onPress={() => {
                                  this.gotoForgottenPass()
                             }}>
                                  <Text style={style.lostpassword}>
                                       {I18n.t("FORGOTTEN_PASSWORD")}
                                  </Text>
                             </TouchableOpacity>
                             <View style={style.contentSwitch}>
                                  <SwitchSelector options={this.options}
                                                  initial={0}
                                                  buttonColor={theme.accentLight}
                                                  backgroundColor={theme.primaryDark}
                                                  textColor='white'
                                                  bold={true}
                                                  hasPadding
                                                  height={32}
                                                  style={style.switch}
                                                  onPress={(value) => {
                                                       this.StartBackgroundColorAnimation(value)
                                                  }}/>
                             </View>
                             <Button style={style.loginBtn1}
                                     isLoading={this.state.isLoging}
                                     onPress={() => {
                                          this.connectClicked()
                                     }}
                             >
                                  <Text style={style.loginBtnText2}>{I18n.t("CONNECT_USER")}</Text>
                             </Button>
                             <View style={separator.container}>
                                  <View style={separator.line}/>
                                  <Text style={separator.text}>{I18n.t("OR_BIG")}</Text>
                                  <View style={separator.line}/>
                             </View>
                             <Button style={style.loginBtn}
                                     onPress={() => {
                                          this.gotoTypeCreated()
                                     }}
                             >
                                  <Text style={style.loginBtnText}>{I18n.t("CREATE_ACCOUNT")} </Text>
                             </Button>
                        </View>

                   </ScrollView>

              </Animated.View>

          )
     }

     gotoForgottenPass() {
          this.props.navigation.push(route.forgotpass, {
               type: this.state.typeaccount,
          })
     }

     connectClicked() {

          if (this.state.password === null || this.state.password === undefined || this.state.password.length < 3 || this.state.password.lenght < 3) {
               this.passRef.shake(800)
          } else {
               this.setState(previousState => {
                    return {isLoging: !previousState.isLoging};
               })
               login(this.state.enterPhone, this.state.password, this.state.typeaccount).then((responseJson) => {
                    console.warn(responseJson)

                    if (responseJson.success === 1) {
                         this.setState(previousState => {
                              return {isLoging: !previousState.isLoging};
                         })
                         let user = responseJson;
                         if (!user.error) {
                              if (user.etat === "1" || user.etat === 1) {
                                   user.indicatif =  this.state.indicatif;
                                   saveNewuser(user);
                                   this.setState({user: user})

                                   Alert.alert(
                                       I18n.t("CONNEXION_SUCCESSFUL"),
                                       I18n.t("CONNEXION_SUCCESSFULL_TEXT"),
                                       [
                                            {
                                                 text: 'Ok', onPress: () => {
                                                      this.setState(previousState => {
                                                           return {isLoging: !previousState.isLoging};
                                                      })
                                                      this.gotoHome()
                                                 }
                                            }
                                       ],
                                       {cancelable: false}
                                   )
                              } else {
                                   if (user.category !== 'super') {
                                        this.props.navigation.push(route.activateaccount, {
                                             type: this.state.typeaccount,
                                             user: user
                                        })

                                   } else {
                                        if (user.etat_demande === 0 || user.etat_demande === '0') {
                                             Alert.alert(
                                                 I18n.t('DONT_VALIDATE_ACCOUNT'),
                                                 I18n.t('UNVALIDATE_ACCOUNT_TEXT'),
                                                 [
                                                      {
                                                           text: 'Ok', onPress: () => {
                                                           }
                                                      }
                                                 ],
                                                 {cancelable: false}
                                             )
                                        } else {
                                             this.props.navigation.push(route.activateaccount, {
                                                  type: this.state.typeaccount,
                                                  user: user
                                             })
                                        }
                                   }
                              }
                         } else {
                              this.setState(previousState => {
                                   return {isLoging: !previousState.isLoging};
                              })
                              Alert.alert(
                                  I18n.t("UNABLE_TO_CONNECT_TITLE"),
                                  I18n.t('TEXT_NETWORK_UNABLE')
                                  ,
                                  [
                                       {
                                            text: I18n.t("NO"), onPress: () => {
                                                 BackHandler.exitApp()
                                            }
                                       },
                                       {
                                            text: I18n.t("YES"), onPress: () => {
                                                 this.connectClicked()
                                            }
                                       }

                                  ],
                                  {cancelable: false}
                              )
                         }

                    } else if (responseJson === null) {
                         this.setState(previousState => {
                              return {isLoging: !previousState.isLoging};
                         })

                    } else {
                         console.log(responseJson)
                         let message = '';
                         switch (responseJson.error) {
                              case 1:
                                   this.phoneRef.shake(1200);
                                   this.passRef.shake(1200);
                                   message = I18n.t("UNABLE_TO_CONNECT")
                                   break;
                              case -1:
                                   this.phoneRef.shake(1200);
                                   message = I18n.t('WRONG_PHONE_NUMBER')
                                   break;
                              case -2:
                                   message = I18n.t('WRONG_PHONE_NUMBER');
                                   this.phoneRef.shake(1200);
                                   break;
                              case -3:
                                   message = I18n.t("WRONG_PASSWORD")
                                   this.passRef.shake(1200);
                                   break;
                              default:
                                   this.passRef.shake(1200);
                                   message = null
                                   break;
                         }

                         if (message === null) {
                              Alert.alert(
                                  I18n.t("UNABLE_TO_CONNECT_TITLE"),
                                  I18n.t('TEXT_NETWORK_UNABLE')
                                  ,
                                  [
                                       {
                                            text: I18n.t("NO"), onPress: () => {
                                                 BackHandler.exitApp()
                                            }
                                       },
                                       {
                                            text: I18n.t("YES"), onPress: () => {
                                                 this.connectClicked()
                                            }
                                       }

                                  ],
                                  {cancelable: false}
                              )
                         } else {
                              Alert.alert(
                                  I18n.t("UNABLE_TO_CONNECT_TITLE"),
                                  message
                                  ,
                                  [

                                       {
                                            text: "OK", onPress: () => {
                                            }
                                       }

                                  ],
                                  {cancelable: false}
                              )
                              this.setState(previousState => {
                                   return {
                                        isLoging: !previousState.isLoging,
                                        snackVisible: true, snackText: message
                                   };
                              })
                              setTimeout(() => {
                                   this.setState({snackVisible: false})
                              }, 2000)
                         }

                    }
               })
                   .catch((e) => {
                        this.setState(previousState => {
                             return {isLoging: !previousState.isLoging};
                        })
                        Alert.alert(
                            I18n.t("UNABLE_TO_CONNECT_TITLE"),
                            I18n.t('TEXT_NETWORK_UNABLE')
                            ,
                            [
                                 {
                                      text: I18n.t("NO"), onPress: () => {
                                           BackHandler.exitApp()
                                      }
                                 },
                                 {
                                      text: I18n.t("YES"), onPress: () => {
                                           this.connectClicked()
                                      }
                                 }

                            ],
                            {cancelable: false}
                        )

                   })
          }
     }
}

const separator = StyleSheet.create({
     line: {
          height: 1.5,
          flex: 1,
          backgroundColor: 'white',
          marginLeft: 30,
          marginRight: 30
     },

     text: {
          color: 'white',
          fontWeight: 'bold',

     },
     container: {
          flexDirection: 'row',
          alignItems: 'center'
     },
     btnContainer: {
          flexDirection: 'column',
          justifyContent: 'center',

     },
})
const style = StyleSheet.create({
     container: {
          flex: 1,
          justifyContent: "center"
     },
     switch: {
          margin: 15,
     },
     contentSwitch: {
          width: responsiveWidth(70),
          alignItems: 'center',
          alignSelf: "center",
          marginTop: 10,
          marginLeft: 10
     },
     lostpassword: {
          color: 'white',
          alignSelf: 'flex-end',

          marginTop: 60,
          fontWeight: 'bold',
          marginRight: 20
     },
     logoContaner: {
          flexDirection: 'row',
          justifyContent: 'center',
          alignItems: 'center',
     },
     logo: {
          width: responsiveWidth(90),
          resizeMode: "contain"
     },
     title: {
          fontSize: responsiveFontSize(4),
          alignSelf: 'center',
          fontWeight: 'bold',
          color: 'white',
     },
     loginBtnText: {
          color: theme.primary,
          fontWeight: 'bold',
          fontSize: 15

     },

     loginBtnText2: {
          color: "white",
          fontWeight: 'bold',
          fontSize: 15

     },

     loginBtn: {
          width: widthButton,
          height: 48,
          alignSelf: 'center',
          marginTop: 20,
          borderRadius: responsiveHeight(4),
          backgroundColor: 'white',
          borderColor: 'transparent',
     },

     loginBtn1: {
          width: widthButton,
          marginTop: responsiveHeight(2),
          height: 48,
          alignSelf: 'center',
          borderRadius: responsiveHeight(4),
          backgroundColor: theme.accentLight,
          borderColor: 'transparent',
     },

     input: {
          width: responsiveWidth(70),
          alignSelf: 'center',
          marginTop: 5,

     },
     labelInput: {
          color: "white",
          fontWeight: 'normal',
     }
})
