import * as React from 'react';
import Chip from '@mui/material/Chip';
import TextField from '@mui/material/TextField';
import Autocomplete from '@mui/material/Autocomplete';
import { FormHelperText } from '@mui/material';
import { Controller, useFormContext } from 'react-hook-form';
import { useEffect } from 'react';

interface IProps {
  name: string,
  label: string,
  options: any,
  defaultValue: any
}

const RHFAutocompleteTags = ({ name, label, options, defaultValue, ...rest }: IProps) => {
  const { control } = useFormContext();
  const fixedOptions: any = [];
  const [value, setValue] = React.useState([...fixedOptions]);

  useEffect(() => {
      setValue(defaultValue)
  }, [options, defaultValue])  

  return (
    <Controller
      name={name}
      control={control}
      render={({ field: { onChange }, fieldState: { error } }) => {
        return (
          <>
            <Autocomplete
              multiple
              id="fixed-tags-demo"
              value={value}
              onChange={(event, newValue) => {
                setValue([
                  ...fixedOptions,
                  ...newValue.filter((option) => fixedOptions.indexOf(option) === -1),
                ]);
                onChange(newValue);
              }}
              isOptionEqualToValue={(option, value)=>{
                return option.optionID === value.optionID
              }}
              options={options}
              getOptionLabel={(option: { optionID: string, optionLabel: string }) => `${option.optionLabel}` || ""}
              renderTags={(tagValue, getTagProps) =>
                tagValue.map((option, index) => (
                  <React.Fragment key={index}>
                    <Chip
                      label={option?.optionLabel}
                      {...getTagProps({ index })}
                    />
                  </React.Fragment>
                ))
              }
              renderInput={(params) => (
                <TextField {...params} label={label} placeholder={label} />
              )}
            />
            {!!error && (
              <FormHelperText error sx={{ px: 2 }}>
                {error.message}
              </FormHelperText>
            )}
          </>
        );
      }}
    />

  );
}

export default RHFAutocompleteTags;