import React from 'react';

import type { GeneralSizeProp } from '@/mui/types';

import { getInputPropsByName } from '@/modules/@common/Form/helpers';
import { isNumber } from '@/modules/@common/helpers/number';
import { loadFromLastDaysSelector, schemeSelector } from '@/modules/feeds/Editor/redux/selectors';
import { removeErrorByPropAction, setAction } from '@/modules/feeds/Editor/redux/slices';

import { useFormSettings } from '@/modules/@common/Form';
import { useAppDispatch, useAppSelector } from '@/modules/@common/store/hooks';
import { NumberField } from '@/mui/components';

type PropTypes = {
  disabled?: boolean;
};

function LoadFromLastDays({ disabled = false }: PropTypes) {
  const dispatch = useAppDispatch();
  const settings = useFormSettings();
  const size = settings.size as GeneralSizeProp;

  const scheme = useAppSelector(schemeSelector);
  const loadFromLastDays = useAppSelector(loadFromLastDaysSelector);

  return (
    <NumberField
      size={size}
      min={1}
      step={1}
      placeholder="Enter Lookback"
      value={loadFromLastDays}
      disabled={disabled}
      {...getInputPropsByName(scheme, ['loadFromLastDays'])}
      onFocus={() => dispatch(removeErrorByPropAction(['loadFromLastDays']))}
      onChange={(e) => {
        const value = parseInt(e.target.value, 10);
        dispatch(setAction({ loadFromLastDays: isNumber(value) ? value : ('' as unknown as number) }));
      }}
    />
  );
}

export default LoadFromLastDays;
