import { Dispatch } from 'redux';
import {
  FormEditorAction,
  Path,
  setFromDate,
  setInpTyp,
  setToDate
} from './types';
import { InpTyp, TxtEditor, inpTyps } from './PktEl';
import { PktDateEditor } from './PktEl';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { isNumber } from './common';
import React from 'react';
import TextField from './TextField';

type DateElProps = ReturnType<typeof mapDispatchToProps> & {
  el: PktDateEditor;
  path: Path;
  children: React.ReactNode;
};

const DateEl: React.FC<DateElProps> = (props) => {
  const { el, path, children, setFromDate, setToDate, setInpTyp } = props;
  const setFrom = (val: string) => {
    setFromDate(path, parseInt(val));
  };
  const setTo = (val: string) => {
    setToDate(path, parseInt(val));
  };
  const setTyp = (val: InpTyp | 'none') => {
    setInpTyp(path, val as InpTyp | 'none');
  };
  return (
    <div className='pkt-el pkt-date'>
      {children && <div className='children'>{children}</div>}
      {el.editing ? (
        <>
          <label htmlFor={'inptyp-' + el.uuid}>Eingabetyp</label>
          <select
            className='pkt-txt-inptyp-input'
            id={'inptyp-' + el.uuid}
            onChange={(event) => {
              setTyp(event.target.value as InpTyp | 'none');
            }}
            defaultValue={el.inptyp ?? 'none'}
          >
            <option value='none'>--</option>
            {inpTyps.map((impTyp) => (
              <option value={impTyp} key={impTyp}>
                {impTyp}
              </option>
            ))}
          </select>
          <TextField
            label='Von'
            currentValue={el.range[0].toString()}
            validate={isNumber}
            setValue={setFrom}
          />
          <TextField
            label='Bis'
            currentValue={el.range[1].toString()}
            validate={isNumber}
            setValue={setTo}
          />
        </>
      ) : (
        <span>
          Date from {el.range[0]} to {el.range[1]}
        </span>
      )}
    </div>
  );
};

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

function mapDispatchToProps(dispatch: Dispatch<FormEditorAction>) {
  return bindActionCreators({ setFromDate, setToDate, setInpTyp }, dispatch);
}

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