import React, { useRef, useEffect } from 'react';
import { Field } from 'react-final-form';
import classNames from 'classnames/bind';
import { required, composeValidators } from 'store/utils/validation';
import GenericFields from 'components/formHelpers/GenericFields';
import _ from 'lodash';
import styleIdentifiers from './cellRowForm.scss';

const styles = classNames.bind(styleIdentifiers);

export interface StateProps {}

export interface DispatchProps {}

export interface OwnProps {
  onSubmit: Function;
}

export type CellRowFormProps = StateProps & DispatchProps & OwnProps;

const CellRowForm = (props: CellRowFormProps) => {
  const {
    handleSubmit,
    smallMargin,
    inputName,
    field,
    onClickOutside,
    values,
    initialValues,
  } = props;

  const formRef = useRef(null);

  function checkIfValuesHaveChange(val, initVal) {
    if (field.inputType === 'number') parseInt(initVal, 10);
    return val !== initVal;
  }

  function handleSubmitOnChange() {
    if (field.type === 'select' && !field.multiple) handleSubmit();
  }

  function handleClickOutside(event) {
    if (formRef.current && !formRef.current.contains(event.target)) {
      const haveChange = checkIfValuesHaveChange(
        _.get(values, inputName),
        _.get(initialValues, inputName),
      );
      if (haveChange) handleSubmit();
      else onClickOutside();
    }
  }

  useEffect(() => {
    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  });

  return (
    <form className={styles('CellRowForm')} ref={formRef} onSubmit={handleSubmit}>
      <GenericFields
        propsInput={{
          small: true,
          labelClassName: styles('no-label'),
          className: styles('input-small', smallMargin && 'small-margin'),
          contentWrapperClassName: styles('input-content-wrapper'),
          autoFocus: true,
          onChange: handleSubmitOnChange,
        }}
        edit
        finalForm
        fields={[
          {
            name: inputName,
            // default type
            type: 'string',
            ...field,
            noMargin: true,
          },
        ]}
      />
    </form>
  );
};

export default CellRowForm;
