// form
import { useFormContext, Controller } from 'react-hook-form';
// @mui
import { Autocomplete, AutocompleteProps, FormHelperText, TextField, UseAutocompleteProps } from '@mui/material';
import { useState } from 'react';
import { FilterOptionsState } from '@mui/material/useAutocomplete';

// ----------------------------------------------------------------------

interface IProps {
  name: string,
  label: string,
  options: any,
  getOptionLabel: (option: any) => string,
  isOptionEqualToValue: any,
  disableClearable: boolean,
  freeSolo: boolean,
  renderOption?: any,
  onInputChange?: any,
  onKeyDown?: any,
  onKeyPress?: any,
  noOptionsText?: string,
  popupIcon?: any,
  disabled?: boolean,
  sx?: any,
  sxTextField?: any,
  InputProps?: any,
  onSelect?: (option: any) => void,
  filterOptions?: (options: any[], state: FilterOptionsState<any>) => any[];
}

const RHFAutocompleteV2 = ( {name, label, options, ...rest} : IProps ) => {
  const { control } = useFormContext();
  const {
    sx, sxTextField, InputProps,
    onSelect,
    getOptionLabel, filterOptions, 
    popupIcon,
    isOptionEqualToValue, disableClearable,
    freeSolo, renderOption,
    onInputChange, onKeyDown, onKeyPress,
    noOptionsText, disabled } = rest;

  return (
    <Controller
      name={name}
      control={control}
      render={({ field: { onChange, value }, fieldState: { error } }) => {
        return (
          <>
          <Autocomplete            
            disabled={disabled}
            handleHomeEndKeys
            getOptionLabel={getOptionLabel}
            options={options}
            freeSolo={freeSolo}
            disableClearable={disableClearable}
            isOptionEqualToValue={isOptionEqualToValue}
            value={value}
            filterOptions={filterOptions}
            renderOption={renderOption}
            onInputChange={onInputChange}
            onKeyDown={onKeyDown}
            onKeyPress={onKeyPress}
            sx={sx}
            popupIcon={popupIcon}
            noOptionsText={noOptionsText}
            renderInput={(params) => (
              <TextField
                {...params}
                label={label}
                sx={sxTextField}
                InputProps={{ 
                  ...params.InputProps,
                  ...InputProps
                }}
              />
            )}
            onChange={(e, newValue) => { 
              onChange(newValue);
              onSelect && onSelect(newValue);
            }}
          />

          {!!error && (
            <FormHelperText error sx={{ px: 2 }}>
              {error.message}
            </FormHelperText>
          )}
          </>


        );
      }}
    />
  );



}

export default RHFAutocompleteV2;