import React from 'react';
import PropTypes from 'prop-types';
import {View, Text, ScrollView, Image, Dimensions} from 'react-native';
import {connect} from 'react-redux';
import {FormInput} from 'react-native-elements';
import logo from 'app/assets/images/logo.png';
import {authLogin, authCheckStatus} from 'app/shared/actions/auth';
import {organisationsSetActiveSlug} from 'app/shared/actions/companies';
import ConfigService from '../../ConfigService';
import RaisedButton from '../../components/RaisedButton';
import {showMessage} from 'react-native-flash-message';
import axios from '../../axios-config';

// import {USERNAME, PASSWORD, PUBLIC_USERNAME, PUBLIC_PASSWORD} from 'react-native-dotenv';
const USERNAME = '';
const PASSWORD = '';

import image from '../../assets/images/header1.jpg';
import {KeyboardAwareScrollView} from 'react-native-keyboard-aware-scroll-view';
import NavigationService from '../../shared/services/NavigationService';

class LoginScreen extends React.Component {
  state = {
    checked: false,
    username: USERNAME || '',
    password: PASSWORD || '',
    width: 800,
    height: 800,
    showForm: false,
  };

  componentDidMount() {
    this.checkToken();
    this.setState({
      ...this.state,
      width: Dimensions.get('window').width,
      height: Dimensions.get('window').height,
    });
  }

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

  async checkToken() {
    try {
      const token = await ConfigService.get('authToken');
      console.warn(token);
      this.props.authCheckStatus(token);
    } catch (e) {
      console.log(e);
    }
  }

  tryLogin() {
    const {username, password} = this.state;
    this.props.authLogin(username, password);
  }

  async publicLogin() {
    NavigationService.navigate('appPublic');
  }

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

  render() {
    const {scrollViewContainerStyle, inputStyle} = styles;
    return (
      <View style={{flex: 1, backgroundColor: 'transparent'}}>
        <View>
          <Image
            style={{
              height: this.state.height,
              width: this.state.width,
              position: 'absolute',
              top: 0,
              left: 0,
            }}
            source={image}
          />
        </View>

        <KeyboardAwareScrollView
          style={{flex: 1}}
          containerStyle={scrollViewContainerStyle}>
          <View
            style={{backgroundColor: 'white', padding: 10, paddingBottom: 30}}>
            <View style={{paddingHorizontal: 15}}>
              <View style={{flexDirection: 'row'}}>
                <Image
                  style={{width: 150, height: 100}}
                  resizeMode={'contain'}
                  source={logo}
                />
              </View>
              <View>
                <Text>
                  Met deze app kun je de deelnemende bedrijven bekijken. Heb je
                  inloggevens gekregen? Dan kun je ook jouw route zien en
                  berichten lezen.
                </Text>
                <Text style={{marginTop: 20}}>
                  Wil je alleen door de bedrijven bladeren? Druk op "Bedrijven
                  bekijken".
                </Text>
                <Text>Heb je inloggegevens? Druk op "Ik kan inloggen".</Text>
              </View>
            </View>
            <View
              style={{
                marginTop: 20,
                justifyContent: 'center',
                alignItems: 'flex-start',
              }}>
              <RaisedButton
                color={'#666'}
                title={'Bedrijven bekijken'}
                onPress={() => this.publicLogin()}
              />
            </View>
            {!this.state.showForm && (
              <View
                style={{
                  marginTop: 20,
                  justifyContent: 'center',
                  alignItems: 'flex-start',
                }}>
                <RaisedButton
                  title={'Ik kan inloggen'}
                  onPress={() => this.setState({...this.state, showForm: true})}
                />
              </View>
            )}
            {this.state.showForm && (
              <View>
                <FormInput
                  containerStyle={inputStyle}
                  autoCapitalize={'none'}
                  value={this.state.username}
                  onChangeText={(value) => this.setValue('username', value)}
                  placeholder="Gebruikersnaam"
                />

                <FormInput
                  containerStyle={inputStyle}
                  secureTextEntry={true}
                  textContentType={'password'}
                  autoCapitalize={'none'}
                  value={this.state.password}
                  onChangeText={(value) => this.setValue('password', value)}
                  placeholder="Wachtwoord"
                />
              </View>
            )}
            {this.state.showForm && (
              <View
                style={{
                  marginTop: 20,
                  justifyContent: 'center',
                  alignItems: 'flex-start',
                }}>
                <RaisedButton
                  title={'Inloggen'}
                  onPress={() => this.tryLogin()}
                  disabled={
                    this.props.auth.loading ||
                    this.state.username.length === 0 ||
                    this.state.password.length === 0
                  }
                  loading={this.props.auth.loading}
                />
              </View>
            )}
          </View>
        </KeyboardAwareScrollView>
      </View>
    );
  }
}

const styles = {
  inputStyle: {
    borderWidth: 0.5,
    marginTop: 20,
    paddingHorizontal: 5,
    borderColor: '#999999',
    borderRadius: 5,
  },
  scrollViewContainerStyle: {
    flex: 1,
    alignItems: 'stretch',
    justifyContent: 'space-around',
  },
};

LoginScreen.propTypes = {
  navigation: PropTypes.object,
  auth: PropTypes.object,
  authLogin: PropTypes.func,
  authCheckStatus: PropTypes.func,
};

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

const mapDispatchToProps = {
  authLogin,
  authCheckStatus,
  organisationsSetActiveSlug,
};

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