import React, { Component } from 'react';
import {
  View,
} from 'react-native';
import { FormInput, FormLabel } from 'react-native-elements';
import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view';
import { NavigationActions } from 'react-navigation';
import { connect, Dispatch } from 'react-redux';
import { UserActions } from '../../actions';
import { Employee, RootState, UserBody } from '../../models';
import { PhotoArea } from '../common/';
import { Button, Card, Header } from '../ui';

interface StateProps {
  user: Employee;
  loading: boolean;
  error?: string;
}

interface DispatchProps {
  onSaveBody: (userId: string, data: UserBody) => void;
  onSaveImage: (userId: string, photoPath: string) => void;
  onClose: () => void;
}

interface State extends UserBody {
  photoPath?: string;
}

const CURRENT_YEAR = (new Date()).getFullYear();
const MINIMUM_BIRTH_YEAR = CURRENT_YEAR - 100;
const MAXIMUM_BIRTH_YEAR = CURRENT_YEAR - 10;

class EmployeeProfileEditForm extends Component<StateProps & DispatchProps, State> {

  constructor(props: StateProps & DispatchProps) {
    super(props);
    this.state = {
      ...props.user.body,
      photoPath: props.user.body.avatar,
    };
  }

  validateBirthYear = () => {
    if (this.state.birthYear < MINIMUM_BIRTH_YEAR) {
      this.setState({ birthYear: MINIMUM_BIRTH_YEAR });
    } else if (this.state.birthYear > MAXIMUM_BIRTH_YEAR) {
      this.setState({ birthYear: MAXIMUM_BIRTH_YEAR });
    }
  }

  save = () => {
    const { onSaveBody, onSaveImage, user: { body: { id } } } = this.props;
    if (this.state.photoPath !== this.props.user.body.avatar) {
      onSaveImage(id, this.state.photoPath);
    }
    const { photoPath, ...data } = this.state;
    onSaveBody(id, data);
  }

  renderSaveButton() {
    const { loading } = this.props;
    return (
      <Button
        buttonStyle={{ padding: 8 }}
        loading={loading}
        title={loading ? '' : 'Zapisz'}
        onPress={this.save}
        activityIndicatorStyle={{ height: 25 }}
      />
    );
  }

  render() {
    const { loading } = this.props;
    const body = this.state;
    return (
      <View>
        <Header
          title='Pracownik'
          rightComponent={this.renderSaveButton()}
        />
        <KeyboardAwareScrollView extraHeight={100} enableOnAndroid={true} viewIsInsideTabBar={true}>
          <View style={{ flex: 1, paddingBottom: 80 }}>
            <PhotoArea
              photoUrl={body.avatar}
              onNewPath={(photoPath) => this.setState({ photoPath })}
              editable={true}
            />
            <Card title='Podstawowe informacje' containerStyle={{ marginHorizontal: -12 }}>
              <FormLabel>Imię i nazwisko</FormLabel>
              <FormInput
                value={body.name}
                editable={!loading}
                onChangeText={(name) => this.setState({ name })}
              />
              <FormLabel>O mnie</FormLabel>
              <FormInput
                multiline={true}
                value={body.description}
                editable={!loading}
                onChangeText={(description) => this.setState({ description })}
              />
              <FormLabel>Rocznik</FormLabel>
              <FormInput
                keyboardType='numeric'
                value={body.birthYear && body.birthYear.toString() || ''}
                editable={!loading}
                onEndEditing={() => this.validateBirthYear()}
                onChangeText={(birthYear) => this.setState({ birthYear: parseInt(birthYear, 10) })}
              />
            </Card>
          </View>
        </KeyboardAwareScrollView>
      </View>
    );
  }
}

const mapStateToProps: (state: RootState) => StateProps =
  (state) => ({
    user: state.user as Employee,
    loading: state.network.user.update.loading,
    error: state.network.user.update.error,
  });

const mapDispatchToProps: (dispatch: Dispatch<RootState>) => DispatchProps =
  (dispatch) => ({
    onSaveBody: (userId: string, user: UserBody) =>
      dispatch(UserActions.userProfileEditRequest(userId, user)),
    onSaveImage: (userId, photoPath: string) =>
      dispatch(UserActions.userPhotoUploadRequested(userId, photoPath)),
    onClose: () => dispatch(NavigationActions.back()),
  });
export const EmployeeProfileEdit = connect(mapStateToProps, mapDispatchToProps)(EmployeeProfileEditForm);
