/* eslint-disable react-native/no-inline-styles */
/* eslint-disable no-sequences */
/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 *
 * @format
 * @flow
 */

import React, {Component} from 'react';
import {
  Platform,
  StyleSheet,
  Text,
  View,
  ScrollView,
  Alert,
  FlatList,
  ProgressViewIOS,
  ProgressBarAndroid,
  PickerIOS,
  StatusBar,
} from 'react-native';
import ActionButton from 'react-native-action-button';
import MapView from 'react-native-maps';
import {
  responsiveHeight,
  responsiveWidth,
  responsiveFontSize,
} from 'react-native-responsive-dimensions';
import CardView from 'react-native-cardview';
import {Sae} from 'react-native-textinput-effects';
import FontAwesomeIcon from 'react-native-vector-icons/FontAwesome';
import Button from 'apsl-react-native-button';
import {primary, primaryDark, accent} from '../../utils/theme.json';
import * as Animatable from 'react-native-animatable';
import {isNumber} from 'util';
import {readUser} from './../../webservice/AuthApi';
import {sendDemande} from './../../webservice/HistoryRequestApi';
import {sendDemandeSpecificque} from '../../webservice/HistoryRequestApi';
import {getAgentNetworksList} from '../../webservice/NetworkApi';
import {HelperText, TextInput} from 'react-native-paper';
import I18n from 'react-native-i18n';
import {Dropdown} from 'react-native-material-dropdown-v2';
type Props = {};
const route = require('../../route.json');
import {
  Card,
  CardTitle,
  CardContent,
  CardAction,
  CardButton,
  CardImage,
  Title,
} from 'react-native-material-cards';
export default class HistoryRequester extends Component {
  static navigatorStyle = {
    navBarHidden: true,
  };
  static navigationOptions = {
    drawerLabel: () => null,
    headerTitle: I18n.t('ASK_CREDIT'),
    title: I18n.t('ASK_CREDIT'),
  };
  constructor(props) {
    super(props);
    this.state = this.initState();
    this.updateState();
  }
  handleViewRef = ref => (this.numberView = ref);
  handleMontantRef = ref => (this.montantView = ref);
  initState() {
    return {
      phone: null,
      montant: undefined,
      isSending: false,
      isDisabled: true,
      networks: [],
      user: null,
      visibleError: false,
      currentNetwork: {nt: 1},
      errorAnimation: '',
    };
  }

  onUserCancel() {
    this.props.navigation.goBack();
  }
  onUserSend() {
    var validMontant = true;
    if (!isNumber(this.state.montant) || this.state.montant > 1000000) {
      validMontant = false;
    }
    this.setState({visibleError: !validMontant});
    if (!validMontant) {
      this.montantView.shake(800);
      setTimeout(() => {
        this.setState({visibleError: false});
      }, 3000);
    } else {
      this.setState({isSending: true});
      let title = '';
      let message = '';
      sendDemandeSpecificque(
        this.state.montant,
        this.state.user.phoneTransaction,
        this.state.user.code_membre,
      )
        .then(data => {
          if (data.success !== undefined) {
            if (data.success === 1) {
              (title = I18n.t('DEMAND_SEND')),
                (message = I18n.t('DEMAND_SEND_SUCCESFUL'));
            } else {
              (title = "Erreur survenu lors de l'envoie "),
                (message =
                  "Une erreur est survenu lors de l'envoie de la demande");
            }
          } else {
            (title = "Erreur survenu lors de l'envoie "),
              (message =
                "Une erreur est survenu lors de l'envoie de la demande");
          }
          Alert.alert(title, message, [
            {
              text: 'Ok',
              onPress: () => {
                this.setState({montant: ''});
              },
            },
          ]);
          setTimeout(() => {
            this.setState({isSending: false});
          }, 800);
        })
        .catch(error => {
          (title = "Erreur survenu lors de l'envoie "),
            (message = "Une erreur est survenu lors de l'envoie de la demande");
          Alert.alert(title, message, [{text: 'Ok'}]);
        });
    }
  }
  render() {
    const {user} = this.state;
    return (
      <View
        style={{
          flex: 1,
          alignItems: 'center',
          backgroundColor: 'lightgrey',
          paddingTop: responsiveHeight(10),
        }}>
        <StatusBar translucent={false} />
        {user ? (
          user.category === 'geolocated' ? (
            this.multiNetwork()
          ) : (
            this.simpleAgent()
          )
        ) : (
          <ProgressBarAndroid />
        )}
      </View>
    );
  }
  simpleAgent() {
    let montant = 0;
    if (true) {
      return (
        <View style={{height: 200}}>
          <Card style={{width: responsiveWidth(96), paddingTop: 20}}>
            <CardContent>
              <View>
                <Animatable.View ref={this.handleMontantRef}>
                  <TextInput
                    label={I18n.t('AMOUNT')}
                    keyboardType={'numeric'}
                    style={input.selfitem}
                    ref={ref => {
                      this.refInp = ref;
                    }}
                    mode={'outlined'}
                    inputStyle={input.style}
                    onChangeText={text => {
                      try {
                        let neb = parseInt(text);
                        this.setState({montant: neb, isDisabled: isNaN(neb)});
                      } catch (e) {}
                    }}
                    value={this.state.montant}
                  />
                  <HelperText type="error" visible={this.state.visibleError}>
                    {I18n.t('INVALID_MONTANT')}
                  </HelperText>
                </Animatable.View>
              </View>
            </CardContent>
            <CardAction separator={true} inColumn={false}>
              <CardButton
                onPress={() => {
                  this.onUserCancel();
                }}
                title={I18n.t('CANCEL')}
                color="crimson"
              />
              <CardButton
                onPress={() => {
                  this.onUserSend();
                }}
                title={I18n.t('SEND')}
                color="steelblue"
              />
            </CardAction>
          </Card>
        </View>
      );
    } else {
      return (
        <View style={styles.container}>
          <CardView style={styles.cardInput}>
            <View>
              <Text style={styles.title}>Demande de credit</Text>
              <Animatable.View ref={this.handleMontantRef}>
                <Sae
                  label={I18n.t('AMOUNT')}
                  iconClass={FontAwesomeIcon}
                  iconName={'dollar'}
                  iconColor={primary}
                  inputStyle={input.style}
                  keyboardType={'numeric'}
                  value={this.state.montant}
                  ref={ref => {
                    this.refInp = ref;
                  }}
                  onChangeText={text => {
                    if (text.length > 0) {
                      try {
                        montant = parseFloat(text);
                        this.setState({
                          isDisabled: montant > 0,
                          montant: montant,
                        });
                      } catch (e) {}
                    }
                  }}
                  style={input.selfitem}
                  labelStyle={input.label}
                  autoCapitalize={'none'}
                  autoCorrect={false}
                />
              </Animatable.View>
            </View>
            <View style={styles.btnContainer}>
              <Button
                style={styles.button_1}
                textStyle={styles.button_1_text}
                onPress={() => this.onUserCancel()}>
                {I18n.t('CANCEL')}
              </Button>
              <Button
                isLoading={this.state.isSending}
                isDisabled={!this.state.isDisabled}
                style={styles.button_2}
                ref={r => {
                  this.refBtn = r;
                }}
                textStyle={styles.button_2_text}
                onPress={() => {
                  this.onUserSend();
                }}>
                {I18n.t('SEND')}
              </Button>
            </View>
          </CardView>
        </View>
      );
    }
  }

  multiNetwork() {
    if (true) {
      return (
        <View style={{height: 250, justifyContent: 'center'}}>
          <Card style={{width: responsiveWidth(96), justifyContent: 'center'}}>
            <CardContent>
              <View style={{flex: 1}}>
                <Dropdown
                  label={I18n.t('SELECT_NETWORK')}
                  style={{flex: 1, width: responsiveWidth(70)}}
                  labelExtractor={(item, index) => {
                    return item
                      ? I18n.t('FOR_NUMB') + item.phone + ' (' + item.name + ')'
                      : I18n.t('SELECT_NETWORK');
                  }}
                  valueExtractor={(item, index) => {
                    return item.phone + ' (' + item.name + ')';
                  }}
                  onChangeText={(value, index, data) => {
                    this.setState({currentNetwork: data[index]});
                  }}
                  data={this.state.networks}
                />

                <Animatable.View ref={this.handleMontantRef}>
                  <TextInput
                    label={I18n.t('AMOUNT')}
                    keyboardType={'numeric'}
                    style={input.selfitem}
                    ref={ref => {
                      this.refInp = ref;
                    }}
                    mode={'outlined'}
                    inputStyle={input.style}
                    onChangeText={text => {
                      try {
                        let neb = parseInt(text);
                        this.setState({montant: neb, isDisabled: isNaN(neb)});
                      } catch (e) {}
                    }}
                    value={this.state.montant}
                  />
                  <HelperText type="error" visible={this.state.visibleError}>
                    {I18n.t('INVALID_MONTANT')}
                  </HelperText>
                </Animatable.View>
              </View>
            </CardContent>
            <CardAction separator={true} inColumn={false}>
              <CardButton
                onPress={() => {
                  this.onUserCancel();
                }}
                title={I18n.t('CANCEL')}
                color="crimson"
              />
              <CardButton
                onPress={() => {
                  const {currentNetwork, montant} = this.state;
                  if (
                    currentNetwork !== undefined &&
                    currentNetwork.nt === undefined
                  ) {
                    this.onNetworkSend(
                      currentNetwork.phone,
                      currentNetwork.code_membre,
                      montant,
                    );
                  }
                }}
                title={I18n.t('SEND')}
                color="steelblue"
              />
            </CardAction>
          </Card>
        </View>
      );
    } else {
      return (
        <View style={styles.container2}>
          <CardView style={styles.cardInput2}>
            <View>
              <Text style={styles.title}>{I18n.t('ASK_CREDIT')}</Text>
              <Picker
                selectedValue={this.state.currentNetwork}
                prompt={'Selectionner un reseau'}
                style={{height: 50, width: responsiveWidth(100)}}
                itemStyle={styles.subtitle}
                onValueChange={(itemValue, itemIndex) =>
                  this.setState({currentNetwork: itemValue})
                }>
                {this.state.networks.map((item, index) => {
                  return (
                    <Picker.Item
                      label={
                        item.nt
                          ? 'Selectionner un reseau'
                          : 'Pour le ' + item.phone + ' (' + item.name + ')'
                      }
                      value={item}
                    />
                  );
                })}
              </Picker>
              <Animatable.View ref={this.handleMontantRef}>
                <Sae
                  label={I18n.t('AMOUNT')}
                  iconClass={FontAwesomeIcon}
                  iconName={'dollar'}
                  iconColor={primary}
                  ref={ref => {
                    this.refInp = ref;
                  }}
                  inputStyle={input.style}
                  keyboardType={'numeric'}
                  onChangeText={text => {
                    try {
                      let neb = parseInt(text);
                      this.setState({montant: neb, isDisabled: isNaN(neb)});
                    } catch (e) {}
                  }}
                  style={input.selfitem}
                  labelStyle={input.label}
                  autoCapitalize={'none'}
                  autoCorrect={false}
                />
              </Animatable.View>
            </View>
            <View style={styles.btnContainer}>
              <Button
                style={styles.button_1}
                textStyle={styles.button_1_text}
                onPress={() => this.onUserCancel()}>
                {I18n.t('CANCEL')}
              </Button>
              <Button
                ref={ref => {
                  this.refBtn = ref;
                }}
                isDisabled={this.state.isDisabled}
                style={styles.button_2}
                textStyle={styles.button_2_text}
                onPress={() => {
                  const {currentNetwork, montant} = this.state;
                  if (
                    currentNetwork !== undefined &&
                    currentNetwork.nt === undefined
                  ) {
                    this.onNetworkSend(
                      currentNetwork.phone,
                      currentNetwork.code_membre,
                      montant,
                      this.refInp,
                      this.refBtn,
                    );
                  }
                }}>
                {I18n.t('SEND')}
              </Button>
            </View>
          </CardView>
        </View>
      );
    }
  }

  renderSingleNetwork(item) {
    const itm = item.item;
    console.log(item);
    let refInp = null,
      refBtn = null;
    let montant = 0;
    return (
      <View style={styles.container2}>
        <CardView style={styles.cardInput2}>
          <View>
            <Text style={styles.title}>{I18n.t('ASK_CREDIT')}</Text>
            <Text style={styles.subtitle}>
              {I18n.t('FOR_NUMB')} {itm.phone} ({itm.name})
            </Text>
            <Animatable.View ref={this.handleMontantRef}>
              <Sae
                label={I18n.t('AMOUNT')}
                iconClass={FontAwesomeIcon}
                iconName={'dollar'}
                iconColor={primary}
                ref={ref => {
                  refInp = ref;
                  this.setState({refIn: refInp});
                }}
                inputStyle={input.style}
                value={this.state.montant}
                keyboardType={'numeric'}
                onChangeText={text => {
                  if (text.length > 0) {
                    try {
                      montant = parseFloat(text);
                      this.setStat({montant: montant});
                      if (refBtn) {
                        refBtn.setState({isDisabled: montant > 0});
                        refBtn.isDisabled = montant > 0;
                      }
                    } catch (e) {}
                  }
                }}
                style={input.selfitem}
                labelStyle={input.label}
                autoCapitalize={'none'}
                autoCorrect={false}
              />
            </Animatable.View>
          </View>
          <View style={styles.btnContainer}>
            <Button
              style={styles.button_1}
              textStyle={styles.button_1_text}
              onPress={() => this.onUserCancel()}>
              {I18n.t('CANCEL')}
            </Button>
            <Button
              ref={ref => {
                refBtn = ref;
              }}
              style={styles.button_2}
              textStyle={styles.button_2_text}
              onPress={() => {
                this.onNetworkSend(
                  itm.phone,
                  itm.code_membre,
                  refInp.state.value,
                  refInp,
                  refBtn,
                );
              }}>
              {I18n.t('SEND')}
            </Button>
          </View>
        </CardView>
      </View>
    );
  }
  onNetworkSend(phone, code_membre, text) {
    var validMontant = true;
    let montant = parseFloat(text);
    if (montant === null || !isNumber(montant) || montant > 1000000) {
      validMontant = false;
    }
    this.setState({visibleError: !validMontant});
    if (!validMontant) {
      this.montantView.shake(800);
      setTimeout(() => {
        this.setState({visibleError: false});
      }, 3000);
    } else {
      sendDemandeSpecificque(montant, phone, code_membre).then(data => {
        var title = '';
        var message = '';
        if (data.success !== undefined) {
          if (data.success === 1) {
            title = I18n.t('DEMAND_SEND');
            message = I18n.t('DEMAND_SEND_SUCCESFUL');
          } else {
            title = "Erreur survenu lors de l'envoie ";
            message = "Une erreur est survenu lors de l'envoie de la demande";
          }
        } else {
          title = "Erreur survenu lors de l'envoie ";
          message = "Une erreur est survenu lors de l'envoie de la demande";
        }

        Alert.alert(title, message, [
          {
            text: 'Ok',
            onPress: () => {
              this.setState({montant: ''});
            },
          },
        ]);
      });
    }
  }

  async updateState() {
    let user = await readUser();
    if (user.category === 'geolocated') {
      let networks = await getAgentNetworksList(user.agentId);
      console.log(networks);
      if (networks.success === 1) {
        let net = [this.state.currentNetwork];
        networks.networks.forEach(item => {
          net.push(item);
        });
        this.setState({networks: net});
      }
    }
    this.setState({user: user});
  }
}

const input = StyleSheet.create({
  selfitem: {
    width: responsiveWidth(70),
    alignSelf: 'center',
    marginBottom: 20,
  },
  label: {
    color: primary,
  },
  style: {
    color: 'black',
  },
});
const styles = StyleSheet.create({
  title: {
    backgroundColor: primary,
    color: 'white',
    paddingLeft: 20,
    paddingTop: 10,
    fontWeight: 'bold',
    fontSize: responsiveFontSize(3),
    height: responsiveHeight(10),
  },
  subtitle: {
    color: 'black',
    paddingLeft: 20,
    paddingTop: 10,
    marginBottom: responsiveHeight(3),
    fontWeight: 'bold',
    fontSize: responsiveFontSize(2),
  },
  container: {
    flex: 1,
    backgroundColor: '#EEE',
    justifyContent: 'space-between',
  },

  container2: {
    flex: 1,
    height: responsiveHeight(20),
    backgroundColor: '#EEE',
  },
  btnContainer: {
    flexDirection: 'row',
    paddingRight: 5,
    paddingLeft: 5,
    paddingTop: 5,
    marginBottom: -2.5,
  },
  button_1: {
    flex: 1,
    borderColor: 'transparent',
  },
  button_2: {
    flex: 1,
    borderColor: 'transparent',
    backgroundColor: primary,
    borderRadius: 0,
  },

  button_1_text: {
    color: primary,
    fontWeight: 'bold',
  },

  button_2_text: {
    color: 'white',
    fontWeight: 'bold',
  },
  cardInput: {
    marginLeft: 10,
    marginRight: 10,
    marginTop: responsiveHeight(5),
    width: responsiveWidth(98),
    alignSelf: 'center',
    justifyContent: 'space-between',
    height: responsiveHeight(40),
  },
  cardInput2: {
    marginLeft: 10,
    marginRight: 10,
    marginTop: responsiveHeight(1),
    width: responsiveWidth(98),
    height: responsiveHeight(50),
    alignSelf: 'center',
    justifyContent: 'space-between',
  },
});
