import DateTimePicker from '@react-native-community/datetimepicker';
import Button from 'apsl-react-native-button';
import isEqual from 'lodash/isEqual';
import isNil from 'lodash/isNil';
import React, {Component} from 'react';
import {
    Alert,
    Keyboard,
    PermissionsAndroid,
    Platform,
    ProgressBarAndroid,
    ScrollView,
    StyleSheet,
    Text,
    View
} from 'react-native';
import * as Animatable from 'react-native-animatable';
import Geolocation from 'react-native-geolocation-service';
import I18n from 'react-native-i18n';
import {MaterialDialog} from "react-native-material-dialog";
import {Dropdown} from 'react-native-material-dropdown';
import {responsiveHeight, responsiveWidth} from 'react-native-responsive-dimensions';
import {ProgressDialog} from 'react-native-simple-dialogs';
import {Fumi} from 'react-native-textinput-effects';
import FontAwesomeIcon from 'react-native-vector-icons/FontAwesome';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import {Color} from '../../config/Color';
import {store} from '../../redux/store';
import {identityPieces} from '../../utils/UtilsFunction';
import {
    createIndentificationResetAction,
    getNumberDetailAction,
    getNumberResetAction,
    getUserIdentificationAction,
    updateIndentificationAction
} from '../../webservice/IdentificationApi';
import {getListCountriesActive, getTownInformationName, readUser} from './../../webservice/AuthApi';
import {getPositionInformation} from './../../webservice/MapService';
let theme = require('./../../utils/theme.json');
let route = require('./../../route.json');
const GEOLOCATION_OPTIONS = {enableHighAccuracy: true, timeout: 20000, maximumAge: 1000, useSignificantChanges: true};
const moment = require('moment');
class ModifyIdentificationUser extends Component {
    static navigatorStyle = {
        navBarBackgroundColor: Color.primaryColor,
        statusBarColor: Color.primaryDarkColor,
        navBarTextColor: '#FFFFFF',
        navBarButtonColor: '#FFFFFF'
    };
    static navigationOptions = () => {
        return {
            drawerLabel: () => null,
            headerTitle: I18n.t('IDENTIFICATION'),
            headerTintColor: 'white',
            headerStyle: {
                backgroundColor: Color.primaryColor,
                marginTop: 0,
                color: 'white'
            },
            headerTitleStyle: {
                color: "white"
            },
            title: I18n.t('IDENTIFICATION')
        }
    };
    constructor(props) {
        super(props);
        this.state = {
            enterPhone: null,
            firstname: null,
            lastname: null,
            numeroIdentite: null,
            dateNaissance: null,
            dateExpiration: null,
            numeroTelephone: null,
            networksinglePickerVisible: false,
            confirmpassanim: null,
            isLoging: false,
            countries: [],
            town: [],
            townName: null,
            country: null,
            identityPieces: identityPieces(),
            identityPiecesName: I18n.t((identityPieces()[0]).name),
            snackVisible: false,
            snackText: '',
            disableNetwork: false,
            networks: [],
            showPickerDateNaissance: false,
            showPickerDateExpiration: false,
            modalVisible: true,
            user: null,
            triggerSubmitClick: false,
            triggerNextClick: false,
            displayFirstStep: true,
            displaySecondStep: false,
            userIdentificationData: store.getState().getUserIdentificationReducer.result.response.data
        };
        this.dateNaissanceFumiProps = {};
        this.dateExpirationFumiProps = {};
        this.props.createIndentificationResetAction();
    }
    componentDidMount() {
        this.dateNaissanceFumiProps.value = this.state.userIdentificationData !== null ? moment(this.state.userIdentificationData.birth_date).format('DD-MM-YYYY') : "";
        this.dateExpirationFumiProps.value = this.state.userIdentificationData !== null ? moment(this.state.userIdentificationData.expiry_date_document).format('DD-MM-YYYY') : "";
        readUser().then((user) => {
            if (user) {
                if (user !== undefined) {
                    //this.props.getNumberDetailAction(user.phone);
                    this.setState({
                        user,
                        lastname: this.state.userIdentificationData.firstname + ' ' + this.state.userIdentificationData.lastname,
                        numeroIdentite: this.state.userIdentificationData.id_identity_document
                    });
                }
            }
        });
        if (Platform.OS === 'android') {
            this.requestCameraPermission();
        } else {
            this.watchLocation();
        }
    }
    renderCreateIdentificationResponse() {
        const {result, error} = this.props;
        console.log("PROPS", this.props);
        if (result !== null) {
            if (typeof result.response !== 'undefined') {
                Alert.alert(
                    I18n.t('SUCCESS_IDENTIFICATION'),
                    result.response,
                    [
                        {
                            text: I18n.t("OK"), onPress: () => {
                                this.props.getUserIdentificationAction(this.state.user.phone);
                                this.props.createIndentificationResetAction();
                                this.setState({triggerSubmitClick: false});
                                this.props.navigation.pop();
                            }
                        }
                    ],
                    {cancelable: false}
                )
            }
        }
        if (error !== null) {
            if (typeof error.data !== 'undefined') {
                Alert.alert(
                    I18n.t('ERROR_IDENTIFICATION'),
                    error.data.error,
                    [
                        {
                            text: I18n.t("OK"), onPress: () => {
                                this.props.createIndentificationResetAction();
                                this.setState({triggerSubmitClick: false});
                            }
                        }
                    ],
                    {cancelable: false}
                )
            } else {
                Alert.alert(
                    I18n.t('ERROR_IDENTIFICATION'),
                    JSON.stringify(error),
                    [
                        {
                            text: I18n.t("OK"), onPress: () => {
                                this.props.createIndentificationResetAction();
                            }
                        }
                    ],
                    {cancelable: false}
                )
            }
        }
    }
    componentWillUpdate(nextProps, nextState) {
        let dateNaissance = nextState.dateNaissance || new Date();
        if (this.state.showPickerDateNaissance)
            this.dateNaissanceFumiProps.value = moment(dateNaissance).format('DD-MM-YYYY');
        if (this.state.showPickerDateExpiration)
            this.dateExpirationFumiProps.value = moment(nextState.dateExpiration).format('DD-MM-YYYY');
    }
    componentWillUnmount() {
        this.mounted = false;
        if (this.watchID) Geolocation.clearWatch(this.watchID);
    }
    showErrorDialog() {
        this.setState({modalDialog: false})
        Alert.alert("Une erreur est survenue", "Impossible de récuperer des informations du pays verifier que votre gps est activé," +
            "et que vous êtes connecté à internet puis ressayer", [{
            text: "Recommencer", onPress: () => {
                this.watchLocation()
            }
        }, {
            text: "Annuler", onPress: () => {
                this.props.navigation.popToTop()
            }
        }])
    }
    async watchLocation() {
        Geolocation.getCurrentPosition((position) => {
            this.treatPosition(position)
        }, (e) => {
            this.showErrorDialog()
        }, this.props.geolocationOptions);
        if (!this.watchID) {
            Geolocation.watchPosition((position) => {
                this.treatPosition(position)
            }, (e) => {
                this.showErrorDialog()
            }, this.props.geolocationOptions)
        }
    }
    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({modalDialog: false})
                Alert.alert("Echec à l'autorisation",
                    "L'application n'est pas autorisé à acceder à votre position veuillez verifier que votre GPS est activé et configurer en mode Haute Precision",
                    [{
                        text: "Ok", onPress: () => {
                            this.props.navigation.popToTop()
                        }
                    }])
            }
        } catch (err) {
            this.setState({modalDialog: false})
            Alert.alert("Une erreur est Survenue",
                "Une erreur est survenu lors du demarrage de l'application veuillez relancer l'application",
                [{
                    text: "Ok", onPress: () => {
                        BackHandler.exitApp()
                    }
                }])
        }
    }
    treatPosition(position) {
        const myLastPosition = this.state.myPosition;
        const myPosition = position.coords;
        if (!isEqual(myPosition, myLastPosition)) {
            getPositionInformation(myPosition).then((response) => {
                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})
                                } else if (results[0].address_components[i].types[j] === "locality") {
                                    const name = results[0].address_components[i].short_name;
                                    this.setState({townName: name});
                                    getTownInformationName(name).then((result) => {
                                        let town = null;
                                        if (result instanceof Array) {
                                            town = result[0];
                                        } else {
                                            town = result;
                                        }
                                        this.setState({modalVisible: false, town: new Array(town)});
                                    })
                                }
                            }
                        }
                        getListCountriesActive().then((cnt) => {
                            this.setState({countries: cnt})
                            console.debug(cnt, shortcountry);
                            var found = false
                            for (let i of cnt) {
                                if (i.code_country === shortcountry) {
                                    found = true;
                                    this.setState({modalVisible: false, indicatif: i.code_dial, country: i.name})
                                    /*                                              this.getNetworks(i.code_dial); */
                                }
                            }
                            if (!found) {
                                Alert.alert("Impossible de recupérer vos informations", "Nous n'avons pas pu recuperer les informations de votre pays veuillez contacter les administrateurs", [{text: "OK"}]);
                            }
                        })
                    }
                }
            }).catch((e) => {
                this.showErrorDialog()
            });
            this.setState({myPosition: myPosition});
        }
    }
    onChangeDateNaissance = (event, selectedDate) => {
        let dateNaissance = isNil(this.state.dateNaissance) ? new Date() : this.state.dateNaissance;
        const currentDate = selectedDate || dateNaissance;
        this.setState({
            showPickerDateNaissance: Platform.OS === 'ios' || false,
            dateNaissance: currentDate,
        });
    };
    onChangeDateExpiration = (event, selectedDate) => {
        let dateExpiration = isNil(this.state.dateExpiration) ? new Date() : this.state.dateExpiration;
        const currentDate = selectedDate || dateExpiration;
        this.setState({
            showPickerDateExpiration: Platform.OS === 'ios' || false,
            dateExpiration: currentDate,
        });
    };
    ckeckIfFieldIsOK(champ) {
        return (isNil(champ) || isEqual(champ.length, 0));
    }
    onSubmitIdentityClient = () => {
        const {lastname, numeroIdentite, dateNaissance, dateExpiration, country, townName, identityPiecesName} = this.state;
        if (this.ckeckIfFieldIsOK(lastname))
            this.lastnameAnim.shake(800);
        /*           else if (this.ckeckIfFieldIsOK(dateNaissance))
                       this.datenaissanceAnim.shake(800);
                  else if (this.ckeckIfFieldIsOK(dateExpiration))
                       this.identityDateExpiryAnim.shake(800); */
        else if (this.ckeckIfFieldIsOK(country))
            this.countryAnim.shake(800);
        else if (this.ckeckIfFieldIsOK(townName))
            this.townAnim.shake(800);
        else if (this.ckeckIfFieldIsOK(identityPiecesName))
            this.identityPiecesAnim.shake(800);
        else if (this.ckeckIfFieldIsOK(numeroIdentite))
            this.numeroIdentiteAnim.shake(800);
        else {
            console.log('USER ID', this.state.user.id);
            moment(dateNaissance).format('DD-MM-YYYY')
            this.props.updateIndentificationAction({
                id: this.state.userIdentificationData.id,
                lastname: this.state.lastname,
                firstname: "",
                birth_date: isNil(this.state.dateNaissance) ? this.dateNaissanceFumiProps.value : moment(this.state.dateNaissance).format('DD-MM-YYYY'),
                town: this.state.townName,
                country: this.state.country,
                identity_document: this.state.identityPiecesName,
                id_identity_document: this.state.numeroIdentite,
                expiry_date_document: isNil(this.state.dateExpiration) ? this.dateExpirationFumiProps.value : moment(this.state.dateExpiration).format('DD-MM-YYYY'),
            });
        }
        this.setState({
            triggerSubmitClick: true
        })
    }
    renderLoaderModal() {
        return (
            
                
                    {I18n.t("LOADING_DESCRIPTION_COUNTRY")}
                    
                
            )
    }
    renderLoader = () => {
        return (
            
        )
    }
    renderDateNaissancePicker = () => {
        return (
            
        );
    }
    renderDateExpirationPicker = () => {
        return (
            
        );
    }
    render() {
        console.log("STATE", this.state);
        const {showPickerDateNaissance} = this.state;
        return (
            <>
                {this.state.showPickerDateNaissance && this.renderDateNaissancePicker()}
                {this.state.showPickerDateExpiration && this.renderDateExpirationPicker()}
                {this.state.modalVisible && this.renderLoaderModal()}
                {(this.props.loading || this.props.loadingNumberDetail) && this.renderLoader()}
                {this.state.triggerSubmitClick && this.renderCreateIdentificationResponse()}
                
                     {
                        this.lastnameAnim = comp
                    }}>
                         {
                                  this.setState({lastname})
                              }}
                              style={styles.input}
                        >
                        
                    
                     {
                        this.datenaissanceAnim = comp
                    }}>
                         {
                                  Keyboard.dismiss();
                                  this.setState({showPickerDateNaissance: true})
                              }}
                              {...this.dateNaissanceFumiProps}>
                        
                    
                     {
                        this.countryAnim = comp
                    }}
                                     style={{
                                         width: responsiveWidth(90),
                                         height: 60,
                                         marginTop: 20,
                                         alignSelf: 'center',
                                         borderRadius: 10,
                                         paddingLeft: 20,
                                         paddingRight: 20,
                                         backgroundColor: 'white'
                                     }}>
                         {
                                this.setState({country: value});
                            }}
                            valueExtractor={(value) => {
                                return value.name
                            }}
                            labelExtractor={(value) => {
                                return value.name
                            }}
                        />
                    
                     {
                        this.townAnim = comp
                    }}
                                     style={{
                                         width: responsiveWidth(90),
                                         height: 60,
                                         marginTop: 20,
                                         alignSelf: 'center',
                                         borderRadius: 10,
                                         paddingLeft: 20,
                                         paddingRight: 20,
                                         backgroundColor: 'white'
                                     }}>
                         {
                                this.setState({townName: value});
                            }}
                            valueExtractor={(value) => {
                                return value.name
                            }}
                            labelExtractor={(value) => {
                                return value.name
                            }}
                        />
                    
                     {
                        this.identityPiecesAnim = comp
                    }}
                                     style={{
                                         width: responsiveWidth(90),
                                         height: 60,
                                         marginTop: 20,
                                         alignSelf: 'center',
                                         borderRadius: 10,
                                         paddingLeft: 20,
                                         paddingRight: 20,
                                         backgroundColor: 'white'
                                     }}>
                         {
                                this.setState({identityPiecesName: value});
                            }}
                            valueExtractor={(value) => {
                                return I18n.t(value.name)
                            }}
                            labelExtractor={(value) => {
                                return I18n.t(value.name)
                            }}
                        />
                    
                     {
                        this.numeroIdentiteAnim = comp
                    }}>
                         {
                                  this.setState({numeroIdentite})
                              }}
                              style={styles.input}
                        >
                        
                    
                     {
                        this.identityDateExpiryAnim = comp
                    }}>
                         {
                                  Keyboard.dismiss();
                                  this.setState({showPickerDateExpiration: true})
                              }}
                              {...this.dateExpirationFumiProps}>
                        
                    
                    
                
            >
        )
    }
}
const maptStateToProps = state => ({
    loading: state.createIdentificationReducer.loading,
    result: state.createIdentificationReducer.result,
    error: state.createIdentificationReducer.error,
    loadingNumberDetail: state.getNumberInformationReducer.loading,
    resultNumberDetail: state.getNumberInformationReducer.result,
    errorNumberDetail: state.getNumberInformationReducer.error,
});
const mapDispatchToProps = dispatch => bindActionCreators({
    updateIndentificationAction,
    createIndentificationResetAction,
    getUserIdentificationAction,
    getNumberDetailAction,
    getNumberResetAction
}, dispatch);
export default connect(maptStateToProps, mapDispatchToProps)(ModifyIdentificationUser);
const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: Color.primaryDarkColor,
    },
    textbtnvalide: {
        color: 'white',
        fontWeight: 'bold'
    },
    bigtitle: {
        color: 'white',
        fontSize: 20,
        flex: 1,
        fontWeight: 'bold',
        textAlign: 'center',
        margin: 20,
    },
    subbigtitle: {
        color: 'white',
        fontSize: 17,
        textAlign: 'center',
        margin: 5,
    },
    btnvalide: {
        marginTop: 20,
        marginLeft: 20,
        marginRight: 20,
        borderColor: 'transparent',
        backgroundColor: Color.accentLightColor,
        height: 52
    },
    btnSubmit: {
        marginTop: 20,
        borderColor: 'transparent',
        backgroundColor: Color.accentLightColor,
        height: 52,
        width: "30%",
        marginLeft: 20,
        marginRight: 20,
    },
    input: {
        height: 60,
        marginTop: responsiveHeight(2),
        marginLeft: responsiveWidth(5),
        marginRight: responsiveWidth(5),
        borderRadius: 5,
    }
});