import React from 'react';
import PropTypes from 'prop-types';
import {connect} from 'react-redux';
import Screen from 'app/components/Screen';
import {KeyboardAwareScrollView} from 'react-native-keyboard-aware-scroll-view';
import {
  authLogout,
  authDeletePushNotificationToken,
} from 'app/shared/actions/auth';
import {personalUpdateData} from 'app/shared/actions/personal';
import RaisedButton from '../../components/RaisedButton';
import {View, Text} from 'react-native';
import {FormInput, FormLabel} from 'react-native-elements';
import messaging from '@react-native-firebase/messaging';
import {showMessage} from 'react-native-flash-message/src/index';
import {API_URL} from '../../axios-config';

class ProfileScreen extends Screen {
  state = {
    token: '',
    person: {},
  };

  componentDidMount() {
    this.getToken();

    this.setState({
      ...this.state,
      person: this.props.auth.user.person || {
        firstName: '',
        insertion: '',
        lastName: '',
        phoneNumber: '',
      },
    });
  }

  componentDidUpdate(oldState) {
    if (
      this.props.personal.error &&
      this.props.personal.error !== oldState.personal.error
    ) {
      showMessage({
        message: this.props.personal.error,
        type: 'danger',
      });
    }

    if (
      !this.props.personal.loading &&
      oldState.personal.loading &&
      !this.props.personal.error
    ) {
      showMessage({
        message:
          'Gegevens succesvol aangepast. Het kan een kwartier duren voordat deze wijzigingen zichtbaar zijn voor iedereen.',
        type: 'success',
      });
    }
  }

  async getToken() {
    const token = await messaging().getToken();

    this.setState({
      ...this.state,
      token: token,
    });
  }

  setValue(type, value) {
    this.setState({
      ...this.state,
      person: {...this.state.person, [type]: value},
    });
  }

  logout() {
    this.props.authDeletePushNotificationToken(this.state.token);
    this.props.authLogout();
  }

  render() {
    const {backgroundStyle, scrollContainerStyle} = styles;
    const {requestingData} = this.props.auth;
    return (
      <KeyboardAwareScrollView
        style={backgroundStyle}
        containerStyle={scrollContainerStyle}
        keyboardShouldPersistTaps="handled"
        innerRef={(ref) => (this.scroll = ref)}>
        <Text>
          Hier kun je je persoonlijke gegevens aanpassen. Dit zal dan ook
          zichtbaar worden voor je groepsgenoten.
        </Text>

        <FormLabel style={styles.inputHeader}>Voornaam</FormLabel>
        <FormInput
          containerStyle={styles.inputStyle}
          inputStyle={styles.label}
          autoCapitalize={'none'}
          value={this.state.person.firstName}
          onChangeText={(value) => this.setValue('firstName', value)}
          placeholder="Voornaam"
        />

        <FormLabel style={styles.inputHeader}>Tussenvoegsel</FormLabel>
        <FormInput
          containerStyle={styles.inputStyle}
          inputStyle={styles.label}
          autoCapitalize={'none'}
          value={this.state.person.insertion}
          onChangeText={(value) => this.setValue('insertion', value)}
          placeholder="Tussenvoegsel"
        />

        <FormLabel style={styles.inputHeader}>Achternaam</FormLabel>
        <FormInput
          containerStyle={styles.inputStyle}
          inputStyle={styles.label}
          autoCapitalize={'none'}
          value={this.state.person.lastName}
          onChangeText={(value) => this.setValue('lastName', value)}
          placeholder="Achternaam"
        />

        <FormLabel style={styles.inputHeader}>Telefoonnummer</FormLabel>
        <FormInput
          containerStyle={styles.inputStyle}
          inputStyle={styles.label}
          autoCapitalize={'none'}
          value={this.state.person.phoneNumber}
          onChangeText={(value) => this.setValue('phoneNumber', value)}
          placeholder="Telefoonnummer"
        />

        <View style={styles.buttonContainer}>
          <RaisedButton
            title={'Aanpassen'}
            onPress={() =>
              this.props.personalUpdateData(
                this.props.auth.user.id,
                this.state.person
              )
            }
            loading={this.props.personal.loading}
            disabled={this.props.personal.loading}
          />
        </View>

        <View style={styles.buttonContainer}>
          <RaisedButton
            title={'Uitloggen'}
            onPress={() => this.logout()}
            loading={requestingData}
            disabled={requestingData}
            color={'#c43f3f'}
          />
        </View>
        {process.env.NODE_ENV === 'development' ? (
          <FormLabel selectable>{API_URL}</FormLabel>
        ) : null}
        {process.env.NODE_ENV === 'development' ? (
          <FormLabel selectable>{this.state.token || ''}</FormLabel>
        ) : null}
      </KeyboardAwareScrollView>
    );
  }
}

const styles = {
  backgroundStyle: {
    backgroundColor: 'white',
    paddingVertical: 10,
    paddingHorizontal: 25,
  },
  scrollContainerStyle: {
    flex: 1,
    alignItems: 'stretch',
    justifyContent: 'space-around',
  },
  buttonContainer: {
    marginTop: 20,
    marginBottom: 20,
    justifyContent: 'center',
    alignItems: 'stretch',
  },
  inputStyle: {
    borderWidth: 0.5,
    marginTop: 4,
    paddingHorizontal: 5,
    borderColor: '#999999',
    borderRadius: 5,
  },
  inputHeader: {
    color: '#222',
    marginTop: 20,
  },
  scrollViewContainerStyle: {
    flex: 1,
    alignItems: 'stretch',
    justifyContent: 'space-around',
  },
  label: {
    color: '#222',
  },
};

ProfileScreen.propTypes = {
  auth: PropTypes.object,
  authLogout: PropTypes.func,
  personalUpdateData: PropTypes.func,
  personal: PropTypes.object,
};

const mapStateToProps = (state) => {
  return {
    auth: state.auth,
    personal: state.personal,
  };
};

const mapDispatchToProps = {
  authLogout,
  authDeletePushNotificationToken,
  personalUpdateData,
};

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