import React, { Component } from 'react';

import GeneralModal from '../../components/modals/GeneralModal';
import { speciesMapper } from '../../store/mappers';

class UpdateSpeciesModal extends Component {
  constructor(props) {
    super(props);
    this.state = {
      value: null
    };
    this.onClose = this.onClose.bind(this);
    this.onClickUpdate = this.onClickUpdate.bind(this);
    this.onChange = this.onChange.bind(this);
  }

  onClose() {
    this.props.speciesModal({
      add: this.props.species.add,
      update: null
    });
    this.speciesInput.value = '';
    this.setState({
      value: null
    });
  }

  onClickUpdate() {
    this.props.updateSpecies({
      species: this.speciesInput.value,
      fishId: this.props.species.update.fishId
    });
    this.onClose();
  }

  onChange(value) {
    this.setState({
      value
    });
  }

  componentDidUpdate() {
    if (this.props.species.update && this.state.value === null) {
      this.onChange(this.props.species.update.species);
    }
  }

  render() {
    return (
      <GeneralModal
        title={'Edit Species'}
        show={this.props.species.update}
        onClose={this.onClose}
      >
        <form>
          <div className="form-group mb-3">
            <div className="input-group input-group-alternative">
              <div className="input-group-prepend">
                <span className="input-group-text">
                  <i className="ni ni-collection" />
                </span>
              </div>
              <input
                ref={ref => (this.speciesInput = ref)}
                className="form-control"
                placeholder="Species"
                type="text"
                value={this.state.value || ''}
                onChange={e => this.onChange(e.target.value)}
              />
            </div>
          </div>
          <div className="text-center">
            <button
              type="button"
              className="btn btn-primary my-4"
              onClick={this.onClickUpdate}
            >
              Edit
            </button>
          </div>
        </form>
      </GeneralModal>
    );
  }
}

export default speciesMapper(UpdateSpeciesModal);
