// Copyright 1999-2023. Plesk International GmbH. All rights reserved.

import { useState } from 'react';
import { getSelectedValues } from './getSelectedValues';
const alphaSort = (a, b) => a > b ? 1 : -1;
export const useSelected = _ref => {
  let {
    multiple,
    externalSelected,
    onChange
  } = _ref;
  const getExternal = () => multiple ? getSelectedValues(externalSelected) : externalSelected;
  const [selected, setSelected] = useState(getExternal());
  const [prevExternalSelected, setPrevExternalSelected] = useState(externalSelected);
  if (prevExternalSelected !== externalSelected) {
    setPrevExternalSelected(externalSelected);
    if (selected !== externalSelected) {
      setSelected(getExternal());
    }
  }
  const handleChange = value => {
    let prevSelected = selected;
    let newSelected;
    if (multiple) {
      const isSelectedArray = Array.isArray(selected);
      newSelected = isSelectedArray ? [...selected] : [];
      if (!isSelectedArray || selected.indexOf(value) === -1) {
        newSelected.push(value);
      } else {
        newSelected.splice(selected.indexOf(value), 1);
      }
      newSelected.sort(alphaSort);
      if (isSelectedArray) {
        prevSelected = [...selected].sort(alphaSort);
      }
    } else {
      newSelected = value;
    }
    if (JSON.stringify(prevSelected) !== JSON.stringify(newSelected)) {
      setSelected(newSelected);
      onChange?.(newSelected);
    }
  };
  return {
    selectedValues: getSelectedValues(selected),
    handleChange
  };
};