import { FormControl, FormHelperText, InputLabel, MenuItem, Select } from '@mui/material'
import type { SxProps, Theme } from '@mui/material'

interface SelectOption<T extends string = string> {
  value: T
  label: string
}

interface SelectFieldProps<T extends string = string> {
  label: string
  value: T | ''
  onChange: (value: T) => void
  options: SelectOption<T>[]
  error?: string
  helperText?: string
  required?: boolean
  disabled?: boolean
  size?: 'small' | 'medium'
  fullWidth?: boolean
  sx?: SxProps<Theme>
}

export function SelectField<T extends string = string>({
  label,
  value,
  onChange,
  options,
  error,
  helperText,
  required,
  disabled,
  size = 'small',
  fullWidth = true,
  sx,
}: SelectFieldProps<T>) {
  const labelId = `select-${label.replace(/\s+/g, '-').toLowerCase()}`
  return (
    <FormControl fullWidth={fullWidth} size={size} error={!!error} disabled={disabled} required={required} sx={sx}>
      <InputLabel id={labelId}>{label}</InputLabel>
      <Select
        labelId={labelId}
        value={value}
        label={label}
        onChange={e => onChange(e.target.value as T)}
      >
        {options.map(opt => (
          <MenuItem key={opt.value} value={opt.value}>
            {opt.label}
          </MenuItem>
        ))}
      </Select>
      {(error ?? helperText) && <FormHelperText>{error ?? helperText}</FormHelperText>}
    </FormControl>
  )
}
