import { FormHelperText } from "@mui/material";
import { Autocomplete, TextField } from "@mui/material";
import { Controller, useFormContext } from "react-hook-form";

type Props =  {
    name: string,
    label: string,
    options: string[];
    disabled?: boolean,
}

const RHFAutocompleteNonTerminology = ({ ...props }: Props) => {
  const { control } = useFormContext();

  return (
    <Controller
        name={props.name}
        control={control}
        render={({ field: { onChange, value }, fieldState: { error } }) => {
            let xValue = (value && value.codingCode!=="" ? value : null );

            return (
                <>
                    <Autocomplete
                        handleHomeEndKeys
                        fullWidth
                        options={props.options}
                        value={xValue}
                        disabled={props.disabled}
                        freeSolo={false}
                        onChange={(e, newValue) => { 
                            onChange(newValue);
                        }}
                        renderInput={(params) => (
                            <TextField
                                {...params}
                                label={props.label}
                                name={props.name}
                                error={!!error}
                                variant="outlined"
                            />
                        )}
                    />

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

    />
  )

}

export default RHFAutocompleteNonTerminology