import React from "react";
import {
  FormControl,
  InputLabel,
  Select as MuiSelect,
  MenuItem,
  FormHelperText,
} from "@mui/material";
import PropTypes from "prop-types";

// Custom SelectField field used for selecting types and signs of the email
export default function SelectField(props) {
  const {
    name,
    label,
    value,
    error = null,
    multiple = false,
    onChange,
    options,
  } = props;

  return (
    <FormControl fullWidth variant="outlined" {...(error && { error: true })}>
      <InputLabel>{label}</InputLabel>
      <MuiSelect
        label={label}
        name={name}
        multiple={multiple}
        value={value}
        onChange={onChange}
      >
        {options.map((item) => {
          // map types/signs into items of select field
          let id = item.id;
          let text = item[Object.keys(item)[1]]; // get key of second value and load its value
          return (
            <MenuItem key={id} value={id}>
              {text}
            </MenuItem>
          );
        })}
      </MuiSelect>
      {error && <FormHelperText>{error}</FormHelperText>}
    </FormControl>
  );
}

SelectField.propTypes = {
  name: PropTypes.string.isRequired,
  label: PropTypes.string.isRequired,
  // value can be one of type number (id of item), or array of selected values
  value: PropTypes.oneOfType([
    PropTypes.number,
    PropTypes.arrayOf(PropTypes.number),
  ]).isRequired,
  // boolean if multiple values can be selected
  multiple: PropTypes.bool,
  /* error msg */
  error: PropTypes.string,
  /* value change handler */
  onChange: PropTypes.func.isRequired,
  /* objects, that will be displayed in select field */
  options: PropTypes.arrayOf(PropTypes.object).isRequired,
};
