import Button from 'apsl-react-native-button';
import React, {Component} from 'react';
import {
     Alert,
     Image,
     PermissionsAndroid,
     Platform,
     ProgressBarAndroid,
     ScrollView,
     StyleSheet,
     Text,
     View
} from 'react-native';
import * as Animatable from 'react-native-animatable';
import Dialog from "react-native-dialog";
import {TouchableOpacity} from 'react-native-gesture-handler';
import I18n from 'react-native-i18n';
import ImagePicker from 'react-native-image-crop-picker';
import {responsiveHeight, responsiveWidth} from 'react-native-responsive-dimensions';
import {Fumi} from 'react-native-textinput-effects';
import FontAwesomeIcon from 'react-native-vector-icons/FontAwesome';
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
import {Color} from '../../config/Color';
import isNil from 'lodash/isNil';
import isEqual from 'lodash/isEqual';
import {MaterialDialog} from "react-native-material-dialog";
import {getListCountriesActive, getTownInformationName, readUser} from './../../webservice/AuthApi';
import {FontWeight, Typography} from '../../config/typography';
import {connect} from 'react-redux';
import Geolocation from 'react-native-geolocation-service';
import {bindActionCreators} from 'redux';
import {ProgressDialog} from 'react-native-simple-dialogs';
import {
     getUserIdentificationAction,
     getUserIdentificationResetAction,
     validateIdentificationAction,
     validateIdentificationResetAction
} from '../../webservice/IdentificationApi'
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 ValidateIdentification extends Component {
     static navigatorStyle = {
          navBarBackgroundColor: Color.primaryColor,
          statusBarColor: Color.primaryDarkColor,
          navBarTextColor: '#FFFFFF',
          navBarButtonColor: '#FFFFFF'

     };

     static navigationOptions = () => {
          return {
               drawerLabel: () => null,
               headerTitle: I18n.t('VALIDATE_IDENTIFICATION_DESCRIPTION'),
               headerTintColor: 'white',
               headerStyle: {
                    backgroundColor: Color.primaryColor,
                    marginTop: 0,
                    color: 'white'
               },
               headerTitleStyle: {
                    color: "white"
               },
               title: I18n.t('VALIDATE_IDENTIFICATION_DESCRIPTION'),
          }
     };

     constructor(props) {
          super(props);
          this.state = {
               numeroTelephone: null,
               image: null,
               displayImage: false,
               idNetwork: null,
               idUser: null,
               idIdentification: null,
               displayUploadButtons: false,
               triggerSubmitClick: false,
               triggerValidateClick: false,
               isIdentified: false,
               modalVisible: true,
               isIdentifiedValidated: false,
               userId: null,
               isLoging: false,
               countries: [],
               town: [],
               townName: null,
               country: null,

               datatoSend: null
          };
          this.dataToSendTemp = new FormData();
          this.props.getUserIdentificationResetAction();
          this.props.validateIdentificationResetAction();
     }

     componentDidMount() {
          readUser().then((user) => {
               if (user) {
                    if (user !== undefined) {
                         this.setState({ user });
                    }
               }
          });

          if (Platform.OS === 'android') {
               this.requestCameraPermission();
          } else {
               this.watchLocation();
          }
     }
     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;
                                             getTownInformationName(name).then((result) => {
                                                  let town = null;
                                                  if (result instanceof Array) {
                                                       town = result[0];
                                                  } else {
                                                       town = result;
                                                  }

                                                  this.setState({ modalVisible: false });
                                             })
                                        }
                                   }
                              }
                              getListCountriesActive().then((cnt) => {
                                   this.setState({ countries: cnt })
                                   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 });
               /*                if (this.mapRef !== undefined && this.mapRef !== null) {
                                   this.mapRef.animateToCoordinate({
                                        latitude: myPosition.latitude,
                                        longitude: myPosition.longitude
                                   }, 1000);
                                   this.mapRef.animateToRegion({
                                        latitude: myPosition.latitude,
                                        longitude: myPosition.longitude,
                                        latitudeDelta: 0.03,
                                        longitudeDelta: 0.01,
                                   }, 1000)
                              } */
          }

     }

     createFormData = (key, photo) => {
          this.dataToSendTemp.append(key, {
               name: photo.path.split('/').pop(),
               type: photo.mime,
               uri:
                    Platform.OS === "android" ? photo.path : photo.path.replace("file://", "")
          });

     };

     renderLoader = () => {
          return (
               <ProgressDialog
                    visible={this.props.loadingUserIndentification || this.props.loadingValidateIdentification}
                    title={I18n.t('LOADING')}
                    message={I18n.t('LOADING_INFO')}
               />
          )
     }
     renderLoaderModal() {
          return (
               <MaterialDialog
                    visible={this.state.modalVisible}
                    title={I18n.t("LOADING_INFO")}>
                    <View style={{ justifyContent: 'center', alignItems: 'center' }}>
                         <Text>{I18n.t("LOADING_DESCRIPTION_COUNTRY")}</Text>
                         <ProgressBarAndroid />
                    </View>
               </MaterialDialog>)
     }

     ckeckIfFieldIsOK(champ) {
          return (isNil(champ) || isEqual(champ.length, 0));
     }

     renderGetUserIdentificationResponse = () => {
          const { resultUserIndentification, errorUserIndentification } = this.props;

          if (resultUserIndentification !== null) {
               if (typeof resultUserIndentification.response !== 'undefined') {
                    if (resultUserIndentification.status === 200) {

                         if (resultUserIndentification.response.isIdentifiedValidated) {
                              Alert.alert(
                                   I18n.t('ERROR_IDENTIFICATION'),
                                   I18n.t('ALREADY_VALIDATED'),
                                   [
                                        {
                                             text: I18n.t("OK"), onPress: () => {
                                                  this.props.getUserIdentificationResetAction();
                                                  this.setState({ triggerSubmitClick: false })
                                             }
                                        }

                                   ],
                                   { cancelable: false }
                              )
                         }

                         if (!resultUserIndentification.response.isIdentified && !resultUserIndentification.response.isIdentifiedValidated) {
                              Alert.alert(
                                   I18n.t('ERROR_IDENTIFICATION'),
                                   I18n.t('NOT_IDENTIFIED'),
                                   [
                                        {
                                             text: I18n.t("OK"), onPress: () => {
                                                  this.props.getUserIdentificationResetAction();
                                                  this.setState({ triggerSubmitClick: false });
                                                  this.props.navigation.pop();
                                             }
                                        }

                                   ],
                                   { cancelable: false }
                              )
                         }

                         if (resultUserIndentification.response.isIdentified && !resultUserIndentification.response.isIdentifiedValidated) {
                              this.setState({
                                   isIdentified: resultUserIndentification.response.isIdentified,
                                   isIdentifiedValidated: resultUserIndentification.response.isIdentifiedValidated,
                                   idIdentification: resultUserIndentification.response.data.id,
                                   idNetwork: resultUserIndentification.response.data.idNetwork,
                                   idUser: resultUserIndentification.response.data.id_user,
                                   displayUploadButtons: true,
                                   triggerSubmitClick: false
                              });

                         }

                    }
               }
          }

          if (errorUserIndentification !== null) {
               if (typeof errorUserIndentification.data !== 'undefined') {
                    Alert.alert(
                         I18n.t('ERROR_LABEL'),
                         errorUserIndentification.data.error,
                         [
                              {
                                   text: I18n.t("OK"), onPress: () => {
                                        this.props.getUserIdentificationResetAction();
                                        this.setState({ triggerSubmitClick: false });
                                        this.props.navigation.pop();
                                   }
                              }

                         ],
                         { cancelable: false }
                    )
               } else {
                    Alert.alert(
                         I18n.t('ERROR_LABEL'),
                         JSON.stringify(errorUserIndentification),
                         [
                              {
                                   text: I18n.t("OK"), onPress: () => {
                                        this.setState({ triggerSubmitClick: false });
                                        this.props.getUserIdentificationResetAction();
                                        this.props.navigation.pop();
                                   }
                              }

                         ],
                         { cancelable: false }
                    )
               }
          }

     }

     componentWillReceiveProps(nextProps: Readonly<P>, nextContext: any) {

          const { resultValidateIdentification, errorValidateIdentification } = nextProps;

          if (resultValidateIdentification !== null) {
               if (typeof resultValidateIdentification.response !== 'undefined') {
                    if (resultValidateIdentification.status === 200) {

                         Alert.alert(
                              I18n.t('VALIDATION_EFFECTUE'),
                              I18n.t('USER_SUCCESSFULLY_VALIDATED'),
                              [
                                   {
                                        text: I18n.t("OK"), onPress: () => {
                                             this.props.validateIdentificationResetAction();
                                             this.setState({ triggerSubmitClick: false });
                                             this.props.navigation.pop();
                                        }
                                   }

                              ],
                              { cancelable: false }
                         )

                    }
               }
          }

          if (errorValidateIdentification !== null) {
               if (typeof errorValidateIdentification.data !== 'undefined') {
                    Alert.alert(
                         I18n.t('ERROR_LABEL'),
                         errorValidateIdentification.data.error,
                         [
                              {
                                   text: I18n.t("OK"), onPress: () => {
                                        this.props.validateIdentificationResetAction();
                                        this.setState({ triggerSubmitClick: false });
                                   }
                              }

                         ],
                         { cancelable: false }
                    )
               } else {
                    Alert.alert(
                         I18n.t('ERROR_LABEL'),
                         JSON.stringify(errorValidateIdentification),
                         [
                              {
                                   text: I18n.t("OK"), onPress: () => {
                                        this.props.validateIdentificationResetAction();
                                        this.setState({ triggerSubmitClick: false });
                                   }
                              }

                         ],
                         { cancelable: false }
                    )
               }
          }

     }

     onSubmitValidationClient = () => {
          const { displayUploadButtons, numeroTelephone } = this.state;

          if (displayUploadButtons) {
               console.log('TRUE', displayUploadButtons);
               this.dataToSendTemp.append('id_network', 1);
               this.dataToSendTemp.append('id_country', 1);
               this.props.validateIdentificationAction(this.dataToSendTemp, this.state.idIdentification);
          } else {
               if (this.ckeckIfFieldIsOK(numeroTelephone))
                    this.numeroTelephoneAnim.shake(800);
               else {
                    this.props.getUserIdentificationAction(numeroTelephone);
               }
          }
     }


     onPicture = ({ uri }) => {
          this.setState({ image: uri, displayCamera: true });
          console.log("URI", uri);
     }

     onBackToCamera = () => {
          this.setState({ image: null, displayCamera: false });
     }

     renderDialogImage = () => {

          return (
               <Dialog.Container contentStyle={{ width: responsiveWidth(80) }} useNativeDriver={true} visible={this.state.displayImage}>

                    <Dialog.Title>{I18n.t('PREVISUALISATION')}</Dialog.Title>

                    <View>
                         <View style={{ width: 50 }} />
                         <View style={{ justifyContent: 'center', alignContent: 'center', alignItems: 'center' }}>
                              <Image source={{ uri: this.state.image.path }} style={{
                                   width: this.state.image.width, height: this.state.image.height, aspectRatio: 1,
                                   resizeMode: 'contain'
                              }} />
                         </View>
                         <View style={{ width: 50 }} />
                    </View>

                    <Dialog.Button bold={true} label={I18n.t('OK')} onPress={() => {
                         this.setState({
                              displayImage: false
                         });
                    }} />
               </Dialog.Container>
          )
     }

     render() {
          console.log("STATE", this.state);
          const { showPickerDateNaissance } = this.state;
          return (
               <>
                    {(this.props.loadingUserIndentification || this.props.loadingValidateIdentification) && this.renderLoader()}
                    {this.state.displayImage && this.renderDialogImage()}
                    {this.state.modalVisible && this.renderLoaderModal()}
                    {this.state.triggerSubmitClick && this.renderGetUserIdentificationResponse()}
                    {/*this.state.triggerValidateClick && this.renderValidationResponse()*/}
                    <ScrollView style={styles.container}>
                         <Text style={styles.subbigtitle}>{I18n.t('CREATE_IDENTIFICATION_TITLE')}</Text>

                         {/*                          <Animatable.View style={{
                              justifyContent: 'center',
                              alignItems: 'center'
                         }} ref={(comp) => { this.nameanim = comp }}>
                              <TouchableOpacity onPress={() => {
                                   this.onBackToCamera();
                                   this.setState({ displayCamera: true })
                              }}>

                                   {
                                        this.state.displayCamera ?
                                             <View style={styles.lottie}>
                                                  {
                                                       this.state.image ?
                                                            <Image source={{ uri: this.state.image }} style={{ flex: 1 }} />
                                                            : <Camera onPicture={this.onPicture} />
                                                  }
                                             </View>
                                             :
                                             <LottieView
                                                  style={styles.lottie}
                                                  source={require('../../datas/json/identity_scan.json')}
                                                  autoPlay
                                                  loop={true}
                                             />
                                   }
                              </TouchableOpacity>
                         </Animatable.View> */}

                         <Animatable.View ref={(comp) => { this.numeroTelephoneAnim = comp }}>
                              <Fumi iconClass={FontAwesomeIcon} iconName={'phone'}
                                   label={`${I18n.t('PHONE_NUMBER')}`}
                                   iconColor={'#f95a25'}
                                   keyboardType='phone-pad'
                                   value={this.state.numeroTelephone === null ? this.state.indicatif : this.state.numeroTelephone}
                                   iconSize={20}
                                   onChangeText={(numeroTelephone) => {
                                        this.setState({ numeroTelephone })
                                   }}
                                   style={styles.input}
                              >
                              </Fumi>
                         </Animatable.View>

                         {
                              this.state.displayUploadButtons &&
                              <View style={{ marginTop: 20, flexDirection: 'row' }}>

                                   <View style={[styles.contentPicker]}>


                                        <View style={[styles.contentPicker]}>
                                             <TouchableOpacity
                                                  style={[styles.contain]}
                                                  onPress={() => {
                                                       ImagePicker.openCamera({
                                                            width: 200,
                                                            height: 200,
                                                            cropping: true,
                                                            useFrontCamera: true
                                                       }).then(image => {
                                                            this.createFormData('user_image', image);
                                                            this.setState({ image, displayImage: true });
                                                       })
                                                  }}
                                                  activeOpacity={0.9}>
                                                  <View style={[styles.contcontainerCenterentLeft]}>
                                                       <View>
                                                            <Icon name='account-circle' color={Color.whiteColor} style={[styles.thumb]} size={80} />
                                                            <View style={[styles.point, { backgroundColor: Color.accentColor }]}>
                                                                 <Icon name='camera-image' color={Color.whiteColor} size={20} />
                                                            </View>
                                                       </View>
                                                  </View>
                                             </TouchableOpacity>

                                             <Text style={[Typography.footnote, FontWeight.semibold], { color: Color.whiteColor }}>{I18n.t('PROFILE_PICTURE')}</Text>
                                        </View>
                                   </View>

                                   <View style={[styles.contentPicker]}>

                                        <View style={[styles.contentPicker]}>
                                             <TouchableOpacity
                                                  style={[styles.contain]}
                                                  onPress={() => {
                                                       ImagePicker.openCamera({
                                                            width: 400,
                                                            height: 281,
                                                            cropping: true,
                                                            useFrontCamera: false
                                                       }).then(image => {
                                                            this.createFormData('document_image_front', image);
                                                            this.setState({ image, displayImage: true });
                                                       })
                                                  }}
                                                  activeOpacity={0.9}>
                                                  <View style={[styles.contcontainerCenterentLeft]}>
                                                       <View>
                                                            <Icon name='credit-card-scan' color={Color.whiteColor} style={[styles.thumb]} size={80} />
                                                            <View style={[styles.point, { backgroundColor: Color.accentColor }]}>
                                                                 <Icon name='camera-image' color={Color.whiteColor} size={20} />
                                                            </View>
                                                       </View>
                                                  </View>
                                             </TouchableOpacity>
                                             <Text style={[Typography.footnote, FontWeight.semibold], { color: Color.whiteColor }}>{I18n.t('FRONT_FACE_CB')}</Text>
                                        </View>
                                   </View>

                                   <View style={[styles.contentPicker]}>
                                        <TouchableOpacity
                                             style={[styles.contain]}
                                             onPress={() => {
                                                  ImagePicker.openCamera({
                                                       width: 400,
                                                       height: 281,
                                                       cropping: true,
                                                       useFrontCamera: false
                                                  }).then(image => {
                                                       this.createFormData('document_image_back', image);
                                                       this.setState({ image, displayImage: true });
                                                  })
                                             }}
                                             activeOpacity={0.9}>
                                             <View style={[styles.contcontainerCenterentLeft]}>
                                                  <View>
                                                       <Icon name='credit-card-off' color={Color.whiteColor} style={[styles.thumb]} size={80} />
                                                       <View style={[styles.point, { backgroundColor: Color.accentColor }]}>
                                                            <Icon name='camera-image' color={Color.whiteColor} size={20} />
                                                       </View>
                                                  </View>
                                             </View>
                                        </TouchableOpacity>
                                        <Text style={[Typography.footnote, FontWeight.semibold], { color: Color.whiteColor }}>{I18n.t('BACK_FACE_CB')}</Text>
                                   </View>

                              </View>
                         }

                         <Button style={styles.btnvalide}
                              textStyle={styles.textbtnvalide}
                              isLoading={this.state.isLoging}
                              onPress={() => {
                                   this.onSubmitValidationClient();
                                   if (this.state.displayUploadButtons)
                                        this.setState({ triggerValidateClick: true });
                                   this.setState({
                                        triggerSubmitClick: true
                                   })
                              }}>
                              {I18n.t('SUBMIT_LABEL')}</Button>

                    </ScrollView>
               </>
          )
     }
}

const maptStateToProps = state => ({
     loadingUserIndentification: state.getUserIdentificationReducer.loading,
     resultUserIndentification: state.getUserIdentificationReducer.result,
     errorUserIndentification: state.getUserIdentificationReducer.error,

     loadingValidateIdentification: state.validateIdentificationReducer.loading,
     resultValidateIdentification: state.validateIdentificationReducer.result,
     errorValidateIdentification: state.validateIdentificationReducer.error,
});

const mapDispatchToProps = dispatch => bindActionCreators({
     getUserIdentificationAction,
     getUserIdentificationResetAction,
     validateIdentificationResetAction,
     validateIdentificationAction
}, dispatch);

export default connect(maptStateToProps, mapDispatchToProps)(ValidateIdentification);

const styles = StyleSheet.create({
     container: {
          flex: 1,
          backgroundColor: Color.primaryDarkColor,
     },
     contain: { flexDirection: "row" },
     containerCenter: {
          flex: 8,
          flexDirection: "row",
          justifyContent: "center",
          alignItems: "center"
     },
     thumb: {
          borderRadius: 30,
          marginRight: 10
     },
     point: {
          width: 25,
          height: 25,
          borderRadius: 11,
          alignItems: "center",
          justifyContent: "center",
          position: "absolute",
          right: 9,
          bottom: 0
     },
     textbtnvalide: {
          color: 'white',
          fontWeight: 'bold'
     },
     bigtitle: {
          color: 'white',
          fontSize: 20,
          flex: 1,
          fontWeight: 'bold',
          textAlign: 'center',
          margin: 20,
     },
     contentPicker: {
          padding: 10,
          borderRadius: 8,
          flex: 1,
          alignItems: "center"
     },
     subbigtitle: {
          color: 'white',
          fontSize: 17,
          textAlign: 'center',
          margin: 5,
     },
     btnvalide: {
          marginTop: 20,
          marginLeft: 20,
          marginRight: 20,
          borderColor: 'transparent',
          backgroundColor: Color.accentLightColor,
          height: 52
     },
     input: {
          height: 60,
          marginTop: responsiveHeight(2),
          marginLeft: responsiveWidth(5),
          marginRight: responsiveWidth(5),
          borderRadius: 5,
     },
     lottie: {
          width: 540,
          height: 300
     },
});
