import {
  Autocomplete,
  Box,
  CircularProgress,
  TextField,
  Typography,
} from '@mui/material'
import { Controller } from 'react-hook-form'
import FormLabel from './FormLabel'

type Option = {
  value: string | any
  label: string | any
}

interface MultiSelectProps {
  control?: any
  label: string
  name: string
  options: { value: string | any; label: string | any }[]
  placeholder?: string
  hookForm?: boolean
  loading?: boolean
  [key: string]: any
  multiple?: boolean
  disabled?: boolean
}

export default function FormAutoCompleteSearch({
  control,
  name,
  options,
  onOpen,
  label,
  loading, // pass this variable when options are from an async operation
  hookForm = true,
  multiple = false,
  disabled = false,
  ...props
}: MultiSelectProps) {
  if (!hookForm) {
    return (
      <Autocomplete
        onOpen={onOpen}
        multiple={multiple}
        value={props.value}
        fullWidth
        onChange={(e, value) => {
          props.onChange(value)
        }}
        disabled={disabled}
        options={options || []}
        getOptionLabel={(option: Option) => option?.label || ''}
        renderInput={(params) => (
          <TextField
            variant="outlined"
            label={<FormLabel label={label} required={props.required} />}
            disabled={disabled}
            {...params}
          />
        )}
        {...props}
      />
    )
  }

  return (
    <Controller
      control={control}
      name={name}
      render={({ field, fieldState: { error } }) => (
        <Box>
          <Autocomplete
            onOpen={onOpen}
            multiple={multiple}
            loading={loading}
            value={field.value}
            fullWidth
            onChange={(e, value) => {
              field.onChange(value)
            }}
            options={options || []}
            getOptionLabel={(option: Option) => option?.label || ''}
            disabled={disabled}
            renderInput={(params) => (
              <TextField
                error={Boolean(error)}
                variant="outlined"
                label={<FormLabel label={label} required={props.required} />}
                disabled={disabled}
                InputProps={{
                  ...params.InputProps,
                  endAdornment: (
                    <>
                      {loading ? (
                        <CircularProgress color="inherit" size={20} />
                      ) : null}
                      {params.InputProps.endAdornment}
                    </>
                  ),
                }}
                {...params}
              />
            )}
          />
          {error && (
            <Typography
              fontSize={12}
              sx={{
                paddingLeft: '2px',
                marginTop: '2px',
              }}
              color="error"
            >
              {error?.message}
            </Typography>
          )}
        </Box>
      )}
    />
  )
}
