import React, { Component } from 'react'
import { StyleSheet, View, Text, Alert, Platform, ScrollView, ProgressBarAndroid } from 'react-native'
import CardView from 'react-native-cardview'
import Button from 'apsl-react-native-button'
import { responsiveHeight, responsiveWidth } from 'react-native-responsive-dimensions'
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
import { updateCreditDemand } from "../../webservice/HistoryRequestApi";
import { readUser } from "../../webservice/AuthApi";
let typesta = 0
let moment = require('moment-timezone')
var colorback = 'white'
import I18n from "react-native-i18n";
import { treatCreditDemand, creditDemandResetReducer } from '../../webservice/CreditTreatDemandApi';
import { treatCancelDemand, creditCancelResetReducer } from '../../webservice/CreditCancelDemandeApi';
import { getAgentNetworksList } from "../../webservice/NetworkApi";
import { Header } from "react-native-elements";
let theme = require('./../../utils/theme.json');
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import Toast from 'react-native-root-toast';
import { Color } from '../../config/Color'
const route = require("./../../route.json");
import Dialog from "react-native-dialog";
import { FontWeight } from '../../config/typography'
import DeviceInfo from 'react-native-device-info'
import { getNanoCreditUniqueDemandsAction, getNanoCreditUniqueDemandsReset } from '../../webservice/user/NanoCreditApi'
import { treatDemandGroupAction, treatDemandGroupReset, cancelDemandGroupAction } from '../../webservice/NanoCreditApi'
import { IlinkEmitter } from '../../utils/events';

class DemandGroupNanoCreditDetail extends Component {

     static navigatorStyle = {
          navBarBackgroundColor: theme.accentLight,
          statusBarColor: theme.accent,
          navBarTextColor: '#FFFFFF',
          navBarButtonColor: '#FFFFFF',
     };
     static navigationOptions = ({ navigation }) => {
          return {
               drawerLabel: () => null,
               title: I18n.t('GROUP') + ' N°' + navigation.getParam("id", "-")
          }
     };

     constructor(props) {
          super(props);
          /*           this.item = this.props.navigation.getParam("item", null);
                    let sta = ''
                    if (this.item.status === '1') {
                         typesta = 1
                         colorback = '#AEAEAE'
                         sta = I18n.t('TREAT_DEMAND')
                    } else if (this.item.status === '0') {
                         colorback = 'green'
                         typesta = 2
                         sta = I18n.t('ACCEPTER_DEMANDE')
                    }
                    else {
                         colorback = '#AEAEAE'
                         typesta = 2
                         sta = I18n.t('REFUSED')
                    } */

          this.state = {
               displayAmountModifyDialog: false,
               /* statut: sta, */
               user: null,
               networks: [],
               loadingTreat: false,
               loadingCancel: false,
               triggerTreatmentClick: false,
               triggerCancelClick: false,
               color: colorback,
               montant: null,
               isBtnModifyAmountEnabled: false,
               id: this.props.navigation.getParam("id", null)
          }
          this.currentLocale = I18n.locale.includes("fr") ? "fr" : "en-gb";
          moment.locale(this.currentLocale);

          this.props.getNanoCreditUniqueDemandsReset();
          this.props.getNanoCreditUniqueDemandsAction(this.state.id);

     }

     componentDidMount() {

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

     }

     displayToast = (message) => {
          Toast.show(message, {
               duration: Toast.durations.LONG,
               position: Toast.positions.BOTTOM,
               backgroundColor: Color.primaryColor,
               shadow: true,
               animation: true,
               hideOnPress: true,
               delay: 0,
               onShow: () => {
                    // calls on toast\`s appear animation start
               },
               onShown: () => {
                    // calls on toast\`s appear animation end.
               },
               onHide: () => {
                    // calls on toast\`s hide animation start.
               },
               onHidden: () => {
                    // calls on toast\`s hide animation end.
               }
          });
     }

     onTreatDemand() {
          this.props.treatDemandGroupReset();
          this.props.treatDemandGroupAction({
               id_demande: this.props.resultGetUniqueDemand.response.id,
               id_user: this.state.user.id
          });
     }

     onCancelDemand = () => {
          this.props.treatDemandGroupReset();
          this.props.cancelDemandGroupAction({
               id_demande: this.props.resultGetUniqueDemand.response.id,
               id_user: this.state.user.id
          });
     }


     renderAlertErrorTreatOrCancelDemand = () => {
          const { errorTreatDemand, resultTreatDemand, resultCancelDemand, errorCancelDemand } = this.props;

          if (errorTreatDemand !== null) {
               if (typeof errorTreatDemand.data !== 'undefined') {
                    Alert.alert(
                         I18n.t("ERROR_TREATMENT_DEMAND"),
                         errorTreatDemand.data.error,
                         [
                              {
                                   text: I18n.t("OK"), onPress: () => {
                                        this.props.treatDemandGroupReset();
                                   }
                              }
                         ],
                         { cancelable: false }
                    );
               }
          }

          if (resultTreatDemand !== null) {
               console.log("resultTreatDemand", resultTreatDemand);
               if (resultTreatDemand.status === 200) {
                    this.displayToast(resultTreatDemand.response);
                    this.props.navigation.goBack();
                    //IlinkEmitter.emit('treatNanoGroupDemand');
                    this.props.treatDemandGroupReset();
               }
          }

     }

     renderLabelState = (state) => {
          if (state === 0)
               return I18n.t('NO_TREAT')
          else if (state === 1)
               return I18n.t('TREAT')
          else
               return I18n.t('REFUSED')
     }

     renderBtn() {
          const { resultGetUniqueDemand } = this.props

          if (resultGetUniqueDemand.response.statut === 1) {
               return (<Button
                    style={{
                         borderColor: 'transparent',
                         borderRadius: 6,
                         marginLeft: 5,
                         marginRight: 5,
                         backgroundColor: 'gray'
                    }}
                    isLoading={this.props.loadingTreatDemand}
                    onPress={() => {
                    }}
                    disabled={true}
                    textStyle={styles.textbtnstyle}
               >
                    {this.renderLabelState(resultGetUniqueDemand.response.statut)}
               </Button>
               )
          }
          else if (resultGetUniqueDemand.response.statut === 2) {
               return (<Button
                    style={{
                         borderColor: 'transparent',
                         borderRadius: 6,
                         marginLeft: 5,
                         marginRight: 5,
                         backgroundColor: 'gray'
                    }}
                    onPress={() => {
                    }}
                    disabled={true}
                    textStyle={styles.textbtnstyle}
               >
                    {this.renderLabelState(resultGetUniqueDemand.response.statut)}
               </Button>
               )
          }

          else {
               return (<View style={{
                    flexDirection: 'row',
                    paddingTop: 10
               }}>

                    <View style={{
                         flex: 1,
                         alignItems: 'center'
                    }}>
                         <Button
                              style={{
                                   borderColor: 'transparent',
                                   borderRadius: 6,
                                   marginLeft: 5,
                                   marginRight: 5,
                                   backgroundColor: 'green'
                              }}
                              isLoading={this.props.loadingTreatDemand}
                              onPress={() => {
                                   this.setState({
                                        triggerTreatmentClick: true
                                   });
                                   this.onTreatDemand();
                              }}
                              textStyle={styles.textbtnstyle}
                         >
                              {I18n.t('ACTION_TREAT_DEMAND')}
                         </Button>
                    </View>

                    <View style={{
                         flex: 1,
                         alignItems: 'center'
                    }}>
                         <Button
                              style={{
                                   borderColor: 'transparent',
                                   borderRadius: 6,
                                   marginLeft: 5,
                                   marginRight: 5,
                                   backgroundColor: Color.redColor
                              }}
                              isLoading={this.props.loadingCancelDemand}
                              onPress={() => {
                                   this.setState({
                                        triggerCancelClick: true
                                   });
                                   this.onCancelDemand();
                              }}
                              textStyle={styles.textbtnstyle}
                         >
                              {I18n.t('REFUSER_DEMANDE')}
                         </Button>
                    </View>
               </View>)
          }
     }

     renderLoader = () => {
          return (
               <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
                    {Platform.OS === 'android'
                         ?
                         (
                              <>
                                   <ProgressBarAndroid />
                                   <Text>{I18n.t('LOADING_DOTS')}</Text>

                              </>
                         ) :
                         <>
                              <ActivityIndicator size="large" color={'#ccc'} />
                              <Text>{I18n.t('LOADING_DOTS')}</Text>
                         </>
                    }
               </View>
          )
     }

     getDemandTypeIcon = (type) => {
          switch (type) {
               case 'creation': return 'account-multiple-plus';
               case 'suppression': return 'account-multiple-minus';
               case 'adhesion': return 'account-multiple-check'
               case 'nano_credit': return 'cash'
               default: return 'account-multiple'
          }
     }


     renderDetail = () => {

          const { resultGetUniqueDemand } = this.props;
          let ago = moment.tz(resultGetUniqueDemand.response.date_creation_groupe, moment.tz.guess()).format();
          let dateDemand = moment.tz(resultGetUniqueDemand.response.date_creation_demande, moment.tz.guess()).format();
          ago = moment(ago);
          dateDemand = moment(dateDemand);

          return (<View style={styles.container}>
               <CardView
                    style={styles.cardcontainer}
               >
                    <Text style={{
                         fontSize: 17,
                         fontWeight: 'bold',
                         color: 'black',
                         marginLeft: responsiveWidth(5)
                    }}>
                         {resultGetUniqueDemand.response.nom}
                    </Text>
                    <View style={{
                         flexDirection: 'row',
                         justifyContent: 'flex-start'
                    }}>
                         <Icon name={this.getDemandTypeIcon(resultGetUniqueDemand.response.type)}
                              size={28}
                              color={theme.accent}
                              style={{
                                   marginLeft: 20
                              }}
                         />
                         <Text style={styles.simpleuser}>{`${I18n.t('TYPE_DEMAND')}: ${resultGetUniqueDemand.response.type}`}</Text>
                    </View>
                    <View style={{
                         flexDirection: 'row',
                         justifyContent: 'flex-start'
                    }}>
                         <Icon name='account'
                              size={28}
                              color={theme.accent}
                              style={{
                                   marginLeft: 20
                              }}
                         />
                         <Text style={styles.simpleuser}>{`${I18n.t('CREATOR')}: ${resultGetUniqueDemand.response.createur}`}</Text>
                    </View>
                    <View style={{
                         flexDirection: 'row',
                         justifyContent: 'flex-start'
                    }}>
                         <Icon name='map-marker'
                              size={28}
                              color={theme.accent}
                              style={{
                                   marginLeft: 20
                              }}
                         />
                         <Text style={styles.simpleuser}>{`${I18n.t('COUNTRY')}: ${resultGetUniqueDemand.response.country}`}</Text>
                    </View>
               </CardView>

               <CardView
                    style={styles.cardcontainer}
               >
                    <View style={{
                         flexDirection: 'row',
                         justifyContent: 'flex-start'
                    }}>
                         <Icon name='account-multiple'
                              size={28}
                              color={theme.accent}
                              style={{
                                   marginLeft: 20
                              }}
                         />
                         <Text style={styles.simpleuser}>{`SPONSOR 1: ${resultGetUniqueDemand.response.sponsor1}`}</Text>
                    </View>
                    <View style={{
                         flexDirection: 'row',
                         justifyContent: 'flex-start'
                    }}>
                         <Icon name='account-multiple'
                              size={28}
                              color={theme.accent}
                              style={{
                                   marginLeft: 20
                              }}
                         />
                         <Text style={styles.simpleuser}>{`SPONSOR 2: ${resultGetUniqueDemand.response.sponsor2}`}</Text>
                    </View>
                    <View style={{
                         flexDirection: 'row',
                         justifyContent: 'flex-start'
                    }}>
                         <Icon name='account-multiple'
                              size={28}
                              color={theme.accent}
                              style={{
                                   marginLeft: 20
                              }}
                         />
                         <Text style={styles.simpleuser}>{`SPONSOR 3: ${resultGetUniqueDemand.response.sponsor3}`}</Text>
                    </View>
               </CardView>

               <CardView style={styles.cardcontainer}>
                    {/* <Text style={{
                         fontSize: 17,
                         fontWeight: 'bold',
                         color: 'black',
                         marginLeft: responsiveWidth(5)
                    }}>{I18n.t('DEMAND_INFO')}</Text>
                    <View style={{
                         flexDirection: 'row',
                         justifyContent: 'flex-start'
                    }}>
                         <Icon name='md-git-branch'
                              size={28}
                              color={theme.accent}
                              style={{
                                   marginLeft: 20
                              }}
                         />
                         <Text style={styles.simpleuser}>{this.item.code_parrain}</Text>
                    </View> */}
                    <View style={{
                         flexDirection: 'row',
                         justifyContent: 'flex-start'
                    }}>
                         <Icon name='code-tags'
                              size={28}
                              color={theme.accent}
                              style={{
                                   marginLeft: 20
                              }}
                         />
                         <Text style={styles.simpleuser}>{resultGetUniqueDemand.response.code_groupe}</Text>
                    </View>
                    <View style={{
                         flexDirection: 'row',
                         justifyContent: 'flex-start'
                    }}>
                         <Icon name='cash'
                              size={28}
                              color={theme.accent}
                              style={{
                                   marginLeft: 20
                              }}
                         />
                         <Text style={styles.simpleuser}>{`${I18n.t('LIMITE_GROUP')}: ${resultGetUniqueDemand.response.limite_credit} ${resultGetUniqueDemand.response.currency_code}`}</Text>
                    </View>
                    <View style={{
                         flexDirection: 'row',
                         justifyContent: 'flex-start'
                    }}>
                         <Icon name='calendar'
                              size={28}
                              color={theme.accent}
                              style={{
                                   marginLeft: 20
                              }}
                         />
                         <Text style={styles.simpleuser}>{`${I18n.t('CREATION_DATE')}: ${ago.format(" Do MMMM YYYY à HH:mm")}`}</Text>
                    </View>
                    <View style={{
                         flexDirection: 'row',
                         alignSelf: 'flex-end',
                         marginRight: 20,
                         justifyContent: 'flex-start'
                    }}>
                         <Icon name='update'
                              size={28}
                              color={theme.accent}
                         />
                         <Text style={{
                              marginLeft: responsiveWidth(2),
                              fontSize: 16,
                              color: theme.accent

                         }}>{dateDemand.fromNow()}</Text>
                    </View>
               </CardView>

               {this.renderBtn()}
          </View>);
     }

     render() {
          console.log("DEMAND GROUP PROPS", this.props);

          return (
               <>
                    {(this.state.triggerTreatmentClick || this.state.triggerCancelClick) && this.renderAlertErrorTreatOrCancelDemand()}
                    {
                         this.props.loadingGetUniqueDemand ?
                              this.renderLoader() :
                              this.props.resultGetUniqueDemand != null ?
                                   this.renderDetail() :
                                   null
                    }
               </>
          );
     }


}

const mapStateToProps = state => ({
     loadingGetUniqueDemand: state.getUniqueDemandsGroupReducer.loading,
     resultGetUniqueDemand: state.getUniqueDemandsGroupReducer.result,
     errorGetUniqueDemand: state.getUniqueDemandsGroupReducer.error,

     loadingTreatDemand: state.treatDemandGroupReducer.loading,
     resultTreatDemand: state.treatDemandGroupReducer.result,
     errorTreatDemand: state.treatDemandGroupReducer.error,
});

const mapDispatchToProps = dispatch => bindActionCreators({
     getNanoCreditUniqueDemandsAction: getNanoCreditUniqueDemandsAction,
     getNanoCreditUniqueDemandsReset: getNanoCreditUniqueDemandsReset,

     treatDemandGroupAction: treatDemandGroupAction,
     cancelDemandGroupAction: cancelDemandGroupAction,
     treatDemandGroupReset: treatDemandGroupReset,

     treatCreditDemand: treatCreditDemand,
     creditDemandResetReducer: creditDemandResetReducer,

     treatCancelDemand: treatCancelDemand,
     creditCancelResetReducer: creditCancelResetReducer
}, dispatch);

export default connect(mapStateToProps, mapDispatchToProps)(DemandGroupNanoCreditDetail);

const styles = StyleSheet.create({
     container: {
          flex: 1,
     },
     btnstyle: {

     },

     inputAmountText: {
          ...Platform.select({
               android: {
                    borderBottomColor: Color.borderColor,
                    borderBottomWidth: 0.5,
               }
          })
     },
     simpleuser: {
          marginLeft: responsiveWidth(2),
          fontSize: 16,
          color: '#3E3E3E'
     },
     textbtnstyle: {
          color: "white",
          fontWeight: "bold",
          fontSize: 18
     },
     cardcontainer1: {
          justifyContent: 'space-evenly',
          flex: 2,
          marginRight: 3,
          marginLeft: 3,

     },
     cardcontainer: {
          justifyContent: 'space-evenly',

          flex: 3,
          margin: 3,
     }
})