import React, { useState } from 'react';
import { useRef } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators, Dispatch } from 'redux';
import TextField from './TextField';
import { NumericEditor } from './PktEl';
import {
  FormEditorAction,
  toggleEditing,
  setHint,
  setProperty,
  removeProperty
} from './types';
import { isEmptyStringOrNumber } from './common';

type NumericElProps = ReturnType<typeof mapDispatchToProps> & {
  el: NumericEditor;
  path: Array<string | number>;
  children: React.ReactNode;
};

const NumericEl: React.FC<NumericElProps> = (props) => {
  const { el, path, children, setHint, setProperty, removeProperty } = props;

  const setMin = (val: string) => {
    if (val === '') {
      removeProperty(path, 'min');
    } else {
      setProperty(path, 'min', parseFloat(val));
    }
  };
  const setMax = (val: string) => {
    if (val === '') {
      removeProperty(path, 'max');
    } else {
      setProperty(path, 'max', parseFloat(val));
    }
  };
  return (
    <div className='pkt-el pkt-numeric'>
      {children && <div className='children'>{children}</div>}
      {el.editing && (
        <>
          <TextField
            label='Min'
            currentValue={el.min?.toString() ?? ''}
            validate={isEmptyStringOrNumber}
            setValue={setMin}
          />
          <TextField
            label='Max'
            currentValue={el.max?.toString() ?? ''}
            validate={isEmptyStringOrNumber}
            setValue={setMax}
          />
        </>
      )}
      <TextField
        isHint={true}
        label={el.editing ? 'Notiz' : ''}
        currentValue={el.hint}
        validate={() => true}
        setValue={(input) => {
          setHint(path, input);
        }}
      />
    </div>
  );
};

const mapStateToProps = (state) => ({});

function mapDispatchToProps(dispatch: Dispatch<FormEditorAction>) {
  return bindActionCreators(
    { toggleEditing, setHint, setProperty, removeProperty },
    dispatch
  );
}

export default connect(mapStateToProps, mapDispatchToProps)(NumericEl);
