import React, { useCallback } from 'react';
import { MenuItem } from '@material-ui/core';
import { SelectOption } from 'common/types';
import MuiSelect from '@material-ui/core/Select';
import { fieldToSelect, SelectProps } from 'formik-material-ui';
import { omit } from 'lodash';
import { useStyles } from './styles/form-item-styles';

export const FormSelect = (
  props: SelectProps & { options: SelectOption[] }
) => {
  const {
    form: { setFieldValue },
    field: { name },
  } = props;

  const classes = useStyles();

  const onChange = useCallback(
    event => {
      const { value } = event.target;
      setFieldValue(name, value);
    },
    [setFieldValue, name]
  );
  return (
    <div className={classes.formItem}>
      <label className={classes.label}>{props.label}</label>
      <MuiSelect {...fieldToSelect(omit(props, 'label'))} onChange={onChange}>
        {props.options.map(({ value, label }) => (
          <MenuItem key={value} value={value}>
            {label}
          </MenuItem>
        ))}
      </MuiSelect>
    </div>
  );
};
