import React, { useCallback, useMemo } from 'react';

import { SelectProps } from '.';
import { StyledHiddenInput } from './Styled';
import { flat, map } from '../../../fp/Array';
import { mapOptions } from '../utils';
import { pipe } from '../../../fp/function';
import { BaseOption } from '../types';

const HiddenInput = <T extends BaseOption>({
  options,
  value,
  onChange,
  onQueryChange,
  name,
}: Pick<
  SelectProps<T>,
  'options' | 'value' | 'onChange' | 'onQueryChange' | 'name'
>) => {
  const flatOptions = useMemo(
    () =>
      pipe(
        options,
        mapOptions,
        map(opt => opt.options),
        flat
      ),
    [options]
  );
  const onChangeInputValue = useCallback(
    e => {
      const foundItem = flatOptions.find(item => item.value === e.target.value);
      if (foundItem !== undefined) {
        onChange(foundItem.value);
        onQueryChange?.(undefined);
      }
    },
    [flatOptions, onChange, onQueryChange]
  );

  return (
    <StyledHiddenInput
      name={name}
      value={value === undefined ? '' : value}
      onChange={onChangeInputValue}
      tabIndex={-1}
    />
  );
};

export default HiddenInput;
