import React,{Component} from 'react'
import {StyleSheet, Text, View, Alert, AsyncStorage, BackHandler, PermissionsAndroid} from 'react-native'
import {Fumi} from 'react-native-textinput-effects'
import {responsiveHeight,responsiveWidth} from 'react-native-responsive-dimensions'
import FontAwesome from 'react-native-vector-icons/FontAwesome'
import Button from  'apsl-react-native-button'
let theme=require('./../../utils/theme.json')
import {getCountryNetwork, reinitpassword} from './../../webservice/AuthApi'
import * as Animatable from 'react-native-animatable';
import I18n from "react-native-i18n"
import Geolocation from "react-native-geolocation-service";
import {getPositionInformation} from "../../webservice/MapService";
import isEqual from 'lodash/isEqual'
let country=require('./../../utils/country_code.json');
import Icon from 'react-native-vector-icons/MaterialIcons';
import _ from 'lodash';

const GEOLOCATION_OPTIONS= { enableHighAccuracy: true, timeout: 20000 }

const route=require("./../../route.json")
export default class ForgottenPassword extends Component{
    static navigatorStyle = {
        drawUnderNavBar: true,
        navBarHidden:true,
        drawUnderStatusBar: false,
        statusBarHidden: true,
        statusBarTextColorScheme: 'light',
    };

    handlePasswordRef=ref=>this.state.passRef=ref;

    constructor(props){
        super(props);
        console.log("RESET PASSWORD PROPS",this.props);
        console.warn("USER TYPE", this.props.navigation.state.params.type, typeof this.props.navigation.state.params.type);
        this.state=this.initState();
    };

    initState(){
        return {
            phone:'',
            passRef:null,
            isSending:false,
        }
    }
    _retrieveData = async () => {
        try {
            const value = await AsyncStorage.getItem('position');
            console.warn(value)
            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.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.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){
        getPositionInformation(myPosition).then((response)=>{
            console.log(response,myPosition)
            if(response.results!==undefined){
                if(response.results.length>0) {
                    let most = response.results[0]
                    let {address_components, formatted_address, place_id} = most
                    this.setState({address: address_components, textadress: formatted_address, place: place_id})
                    let results=response.results;
                    let shortcountry;
                    let mcountry;
                    for (let i=0; i < results[0].address_components.length; i++) {
                        for (let j=0; j < results[0].address_components[i].types.length; j++) {
                            if (results[0].address_components[i].types[j] === "country") {
                                mcountry = results[0].address_components[i];
                                shortcountry=mcountry.short_name;
                                this.setState({shortCountry:mcountry.short_name,longCountry: mcountry.long_name})
                            }
                        }
                    }
                    for (let i of country) {
                        if(i.code=== shortcountry){
                            this.setState({indicatif:i.dial_code,enterPhone:i.dial_code})}}
                }else{

                }
                this.setState({phoneEnabled:true,loadingDialog:false});

            }else{
                console.log(myPosition,response)
                this.showConnexionAlertError()
            }
        }).catch((e)=>{
            console.log(e)

            this.setState({phoneEnabled:true,loadingDialog:false});
            Alert.alert(I18n.t("TITLE_PROBLE_COME"),
                I18n.t("TEXT_UNABLE_TO_GET_COUNTRY_INFO"),[{text:"Ok",onPress:()=>{
                        this.watchLocation()
                    }}],{cancelable:false})
        });
    }

    componentDidMount(){
        this.props.navigation.addListener("didFocus",payload=>{
            this._retrieveData()
            this.requestCameraPermission()
        })
    }
    async requestCameraPermission() {
        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:"Ok",onPress:()=>{
                            BackHandler.exitApp()
                        }}],                            {cancelable:false}
                )
            }
        } catch (err) {
            console.warn("ee",err)
            this.setState({loadingDialog:false})
            Alert.alert(I18n.t("TITLE_ERROR_SURVENU"),
                I18n.t("TEXT_ERROR_START_APPLICATION"),
                [{text:"Ok",onPress:()=>{
                        BackHandler.exitApp()
                    }}],                            {cancelable:false}
            )

        }
    }


    render(){
        return <View style={{
            backgroundColor:this.props.navigation.state.params.type===0?theme.primary:theme.primaryDarkAdvanced,
            flex:1,

        }}>
               <View style={{flexDirection:'row',flex:1}}>
                <Icon.Button name={"keyboard-backspace"}
                color={"white"}
                size={24}
                backgroundColor={this.props.navigation.state.params.type===0?theme.primary:theme.primaryDarkAdvanced}
                onPress={()=>this.props.navigation.pop()}
                />

                </View>
            <View style={{ flex:4, justifyContent:'center',
            alignItems:'center'}} >

            <Text
                style={styles.TitlePassword}
            >
                {I18n.t("FORGOTTEN_PASSWORD")}
            </Text>
            <Text style={styles.subtitlePassword}>
                {I18n.t("TEXT_FORGOTTEN_PASSWORD")}
                </Text>
            <Animatable.View  ref={(ref)=>{this.handlePasswordRef(ref)}}>
                <View style={{flexDirection:'row',justifyContent:'center'}}>
                    <Fumi iconClass={FontAwesome}
                          iconName={'phone'}
                          label={"Indicatif"}
                          style={styles.inputCode}
                          value={this.state.indicatif}
                          iconColor={theme.accent}
                    />
                    <Fumi iconClass={FontAwesome}
                          iconName={'phone'}
                          label={I18n.t("PHONE_NUMBER")}
                          style={styles.input}
                          onChangeText={(text) => { this.setState({phone: text})}}
                          iconColor={theme.accent}
                    />
                </View>
            </Animatable.View>
            <Button style={styles.btnsend}
                    isLoading={this.state.isSending}
                    isDisabled={this.state.isSending}
                    textStyle={styles.btntext} onPress={()=>{this.onRenitPassword()}}>{I18n.t("SEND")}</Button>
        </View>
        </View>
    }

    onRenitPassword() {
       if(this.state.phone.length>0){
           if(this.props.navigation.state.params.type!==null){
               let type= this.props.navigation.state.params.type === 0 ? 'user' : 'agent';
               console.log("Type user send", this.props.navigation.state.params.type);
               this.setState({isSending:true});
               reinitpassword(this.state.indicatif+this.state.phone,type).then((data)=>{

                   this.setState({isSending:false})

                   if(data.error){
                       this.state.passRef.shake(1200);

                       Alert.alert("",data.message,[{text:"Ok"}])

                   }else if(data.success===1) {
                       Alert.alert("", data.message, [{text: "Ok"}])

                       setTimeout(() => {
                           this.props.navigation.popToTop()
                       },1000)
                   }
                   })
           }

       }
    }
}

const styles=StyleSheet.create({
   TitlePassword:{
      marginLeft:20,
        marginRight:20,
        color:'white',
        fontWeight:'bold',
        fontSize:20,
        textAlign:'center'
    },

    subtitlePassword:{
        margin:20,
        color:'white',
        fontSize:20,
        textAlign:'center'
    },
    btntext:{
        color:'white',
        fontWeight:'bold',
        fontSize:17
    },
    btnsend:{
        backgroundColor:theme.accent,
        borderColor:'transparent',
        marginRight:20,
        marginTop:20,
        height:responsiveHeight(8),
        marginLeft:20
    },
    input:{
        height:54,
        marginLeft:3,
        width:responsiveWidth(60),
        marginRight:20,
        borderRadius:10,
        justifyContent:'center',
        textAlign:'center'
    },
    inputCode:{
        height:54,
        width:responsiveWidth(30),
        marginRight:10,
        borderRadius:10,
        justifyContent:'center',
        textAlign:'center'
    }
})