import React, { Component } from 'react';
import {
  LayoutAnimation,
  StyleSheet,
  View,
} from 'react-native';
import { Icon } from 'react-native-elements';
import { NavigationActions } from 'react-navigation';
import { connect, Dispatch } from 'react-redux';
import { AuthActions } from '../../actions';
import { EmployerDetails } from '../../components/employer/EmployerDetails';
import { Button, Colors } from '../../components/ui/';
import { RootState, UserBody } from '../../models';
import { Routes } from '../../navigation';
import { RenderErrorView } from '../RenderError';

interface DispatchProps {
  onLogoutRequested: () => void;
  onEditProfileRequested: () => void;
}

interface StateProps {
  UserBody: UserBody;
}

class ProfileComponent extends Component<StateProps & DispatchProps, { error: boolean }> {

  state = { error: false };

  componentDidCatch() {
    this.setState({ error: true });
  }

  componentWillUpdate() {
    LayoutAnimation.easeInEaseOut();
  }

  renderEditButton() {
    return (
      <View style={styles.editButton}>
        <Icon
          raised={true}
          color={Colors.employer.primary}
          name='edit'
          onPress={this.props.onEditProfileRequested}
        />
      </View>
    );
  }

  renderLogoutButton() {
    return (
      <Button
        containerViewStyle={styles.button}
        buttonStyle={{ height: 50 }}
        title='Wyloguj się'
        onPress={this.props.onLogoutRequested}
      />
    );
  }

  render() {
    if (this.state.error) return <RenderErrorView />;
    return this.props.UserBody && (
      <View style={styles.container}>
        <EmployerDetails
          user={this.props.UserBody}
        />
        {this.renderLogoutButton()}
        {this.renderEditButton()}
      </View>
    );
  }
}

const mapStateToProps: (state: RootState) => StateProps =
  (state) => ({
    UserBody: state.user.body as UserBody,
  });

const mapDispatchToProps: (dispatch: Dispatch<RootState>) => DispatchProps =
  (dispatch) => ({
    onLogoutRequested: () => dispatch(AuthActions.logoutRequested()),
    onEditProfileRequested: () => dispatch(NavigationActions.navigate({ routeName: Routes.EMPLOYER_PROFILE_EDIT })),
  });
export const Profile = connect(mapStateToProps, mapDispatchToProps)(ProfileComponent);

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'space-between',
  },
  editButton: {
    position: 'absolute',
    bottom: 50,
    right: 16,
  },
  button: {
    marginTop: 12,
    marginLeft: 0,
    marginRight: 0,
  },
});
