import React from 'react';
import FormControl from '@mui/material/FormControl';
import InputLabel from '@mui/material/InputLabel';
import Select from '@mui/material/Select';
import FormHelperText from '@mui/material/FormHelperText';
import MenuItem from '@mui/material/MenuItem';

const EnumPicker = ({
  label,
  model,
  field,
  onChange,
  value,
  error,
  helperText,
  optionLabels = {},
}) => {
  const schema = model.schema.properties[field];

  return (
    <FormControl
      component="fieldset"
      error={!!error}
      required={schema.isRequired}
    >
      <InputLabel id={`${field}-select-label`}>
        {label}
      </InputLabel>
      <Select
        labelId={`${field}-select-label`}
        label={label}
        id={`${field}-select`}
        required={schema.isRequired}
        multiple={!schema.isScalar}
        value={value || (schema.isScalar ? '' : [])}
        onChange={({ target: { value } }) => onChange(
          typeof value === 'string' && !schema.isScalar
            ? value.split(',')
            : value,
        )}
      >
        {!schema.isRequired && (
          <MenuItem value={null}>--</MenuItem>
        )}
        {schema.enum.map(opt => (
          <MenuItem key={opt} value={opt}>
            {optionLabels[opt] || opt}
          </MenuItem>
        ))}
      </Select>
      {helperText && (
        <FormHelperText>{helperText}</FormHelperText>
      )}
    </FormControl>
  );
};

export default EnumPicker;
