import Autocomplete from "@mui/material/Autocomplete";
import TextField from "@mui/material/TextField";
import { useMemo } from "react";

export function MultiValueAutocomplete({
  disabled = false,
  getOptionLabel,
  label,
  labels,
  loading = false,
  onChange,
  options = [],
  required = false,
  value
}) {
  const selected = useMemo(() => (Array.isArray(value) ? value : []), [value]);
  const mergedOptions = useMemo(() => {
    const seen = new Set();
    return [...options, ...selected].filter((option) => {
      const key = String(option);
      if (seen.has(key)) {
        return false;
      }
      seen.add(key);
      return true;
    });
  }, [options, selected]);
  const formatOption = getOptionLabel || ((option) => labels?.[String(option)] || String(option));
  const inputRequired = required && selected.length === 0;

  return (
    <Autocomplete
      multiple
      disableCloseOnSelect
      disabled={disabled}
      filterSelectedOptions
      getOptionLabel={formatOption}
      isOptionEqualToValue={(option, selectedOption) => String(option) === String(selectedOption)}
      loading={loading}
      options={mergedOptions}
      renderInput={(params) => (
        <TextField
          {...params}
          label={label}
          slotProps={{
            ...params.slotProps,
            htmlInput: {
              ...params.slotProps?.htmlInput,
              "aria-required": inputRequired || undefined,
              required: inputRequired
            },
            inputLabel: { ...params.slotProps?.inputLabel, required }
          }}
        />
      )}
      size="small"
      value={selected}
      onChange={(_, nextValue) => onChange(nextValue)}
    />
  );
}
