import { FormControl, FormHelperText, InputLabel } from '@mui/material'
import Select from '@mui/material/Select'
import { useTheme } from '@mui/styles'
import { FieldInputProps, FormikProps } from 'formik'
import _get from 'lodash/get'
import _map from 'lodash/map'
import React from 'react'

export interface ISelectOption {
  label: string | number;
  value?: string | number;
  [key: string]: any;
}

export interface ISelectField {
  label: string;

  field: FieldInputProps<any>;
  form: FormikProps<any>;
  theme: 'dark' | 'light';

  // optional
  type?: string;
  selectOptions?: ISelectOption[];
  onChange?: (e: any) => void;
}

interface IOtherProps {
  [key: string]: any;
}

export const NativeSelectField = ({
  label,
  type = 'text',
  field,
  selectOptions = [] as ISelectOption[],
  form: { touched, errors, setFieldValue },
  theme,
  onChange = () => {},
}: ISelectField & IOtherProps) => {
  const isTouched = Boolean(_get(touched, field.name))
  const error = _get(errors, field.name)

  const customTheme: any = useTheme()

  return (
    <FormControl fullWidth={true}>
      <InputLabel
        style={customTheme?.input}
        htmlFor={field.name}
        error={!!error && isTouched}
        shrink={true}
      >
        {label}
      </InputLabel>
      <Select
        id={field.name}
        label={label}
        type={type}
        fullWidth={true}
        error={!!error && isTouched}
        inputProps={{
          id: field.name,
        }}
        native={true}
        className={`Mui-Select ${theme}`}
        MenuProps={{ className: theme }}
        {...field}
        style={customTheme?.input}
        onChange={e => {
          onChange(e)
          setFieldValue(field.name, e.target.value)
        }}
      >
        {_map(selectOptions, option => (
          <option key={option.value} value={option.value} disabled={option.disabled}>
            {option.label}
          </option>
        ))}
      </Select>
      {isTouched && error ? (
        <FormHelperText error={!!error && isTouched}>{error}</FormHelperText>
      ) : null}
    </FormControl>
  )
}
