import * as React from 'react';
import classNames from 'classnames/bind';
import styleIdentifiers from './onBlurInput.scss';

const styles = classNames.bind(styleIdentifiers);

export interface OnBlurInputProps {
  className?: string;
  input: Record<string, any>;
  handleBlur?: Function;
}

interface OnBlurInputState {
  inputValue: string;
}

export default class OnBlurInput extends React.Component<OnBlurInputProps, OnBlurInputState> {
  state = {
    inputValue: '',
  };

  componentDidMount() {
    const { input } = this.props;
    this.setState({ inputValue: input && input.value });
  }

  handleChange = (e: EventHandler) => {
    this.setState({ inputValue: e.target.value });
  };

  handleBlur = (e: EventHandler) => {
    const { input, handleBlur } = this.props;

    const { inputValue } = this.state;

    if (handleBlur) {
      handleBlur(inputValue);
      return;
    }
    input.onBlur(e);
  };

  render() {
    const { inputValue } = this.state;
    const { className, inputType } = this.props;
    return (
      <input
        className={styles('OnBlurInput', className)}
        value={inputValue}
        onChange={this.handleChange}
        onBlur={this.handleBlur}
        type={inputType || 'text'}
      />
    );
  }
}
