import React, { useState, useMemo } from 'react';
import { SortMinor } from '@shopify/polaris-icons';
import { FilterButton } from '../FilterButton/FilterButton.js';
import { ChoiceList } from '../../../ChoiceList/ChoiceList.js';
import { DirectionButton } from './components/DirectionButton/DirectionButton.js';
import { useI18n } from '../../../../utilities/i18n/hooks.js';
import { Tooltip } from '../../../Tooltip/Tooltip.js';
import { Icon } from '../../../Icon/Icon.js';
import { Popover } from '../../../Popover/Popover.js';
import { Box } from '../../../Box/Box.js';

let SortButtonDirection;

(function (SortButtonDirection) {
  SortButtonDirection["Asc"] = "asc";
  SortButtonDirection["Desc"] = "desc";
})(SortButtonDirection || (SortButtonDirection = {}));

function SortButton({
  choices,
  selected,
  onChange,
  disabled,
  onChangeKey,
  onChangeDirection
}) {
  var _selectedChoices$, _selectedChoices$2, _selectedChoices$3, _selectedChoices$4;

  const i18n = useI18n();
  const [active, setActive] = useState(false);
  const [selectedValueKey, selectedDirection] = selected[0].split(' ');

  function handleClick() {
    setActive(pastActive => !pastActive);
  }

  function handleClose() {
    setActive(false);
  }

  function handleChangeChoiceList(sel) {
    if (onChangeKey) {
      const [key] = sel[0].split(' ');
      onChangeKey(key);
    } else {
      onChange(sel);
    }
  }

  function handleChangeDirection(sel) {
    if (onChangeDirection) {
      const [, direction] = sel[0].split(' ');
      onChangeDirection(direction);
    } else {
      onChange(sel);
    }
  }

  const choiceListChoices = useMemo(() => {
    const choiceCategories = choices.reduce((acc, curr) => {
      const alreadyExists = acc.some(option => option.label === curr.label);
      const [, currentValueDirection] = curr.value.split(' ');
      const isSameDirection = currentValueDirection === selectedDirection;

      if (!alreadyExists) {
        return [...acc, curr];
      }

      if (isSameDirection) {
        return acc.map(option => {
          if (option.label === curr.label) {
            return curr;
          }

          return option;
        });
      }

      return acc;
    }, []);
    return choiceCategories;
  }, [choices, selectedDirection]);
  const selectedChoices = choices.filter(choice => {
    const [currentKey] = choice.value.split(' ');
    return currentKey === selectedValueKey;
  });
  const sortButton = /*#__PURE__*/React.createElement(Tooltip, {
    content: i18n.translate('Polaris.IndexFilters.SortButton.tooltip'),
    preferredPosition: "above",
    hoverDelay: 400
  }, /*#__PURE__*/React.createElement(FilterButton, {
    onClick: handleClick,
    "aria-label": i18n.translate('Polaris.IndexFilters.SortButton.ariaLabel'),
    disabled: disabled
  }, /*#__PURE__*/React.createElement(Icon, {
    source: SortMinor,
    color: "base"
  })));
  return /*#__PURE__*/React.createElement(Popover, {
    active: active && !disabled,
    activator: sortButton,
    autofocusTarget: "first-node",
    onClose: handleClose,
    fluidContent: true
  }, /*#__PURE__*/React.createElement(Box, {
    minWidth: "148px",
    padding: "4",
    borderBlockEndWidth: "1",
    borderColor: "border-subdued"
  }, /*#__PURE__*/React.createElement(ChoiceList, {
    title: i18n.translate('Polaris.IndexFilters.SortButton.title'),
    choices: choiceListChoices,
    selected: selected,
    onChange: handleChangeChoiceList
  })), /*#__PURE__*/React.createElement(Box, {
    padding: "4"
  }, /*#__PURE__*/React.createElement(DirectionButton, {
    direction: "asc",
    active: selectedDirection === SortButtonDirection.Asc,
    onClick: handleChangeDirection,
    value: selectedChoices === null || selectedChoices === void 0 ? void 0 : (_selectedChoices$ = selectedChoices[0]) === null || _selectedChoices$ === void 0 ? void 0 : _selectedChoices$.value
  }, selectedChoices === null || selectedChoices === void 0 ? void 0 : (_selectedChoices$2 = selectedChoices[0]) === null || _selectedChoices$2 === void 0 ? void 0 : _selectedChoices$2.directionLabel), /*#__PURE__*/React.createElement(DirectionButton, {
    direction: "desc",
    active: selectedDirection === SortButtonDirection.Desc,
    onClick: handleChangeDirection,
    value: selectedChoices === null || selectedChoices === void 0 ? void 0 : (_selectedChoices$3 = selectedChoices[1]) === null || _selectedChoices$3 === void 0 ? void 0 : _selectedChoices$3.value
  }, selectedChoices === null || selectedChoices === void 0 ? void 0 : (_selectedChoices$4 = selectedChoices[1]) === null || _selectedChoices$4 === void 0 ? void 0 : _selectedChoices$4.directionLabel)));
}

export { SortButton, SortButtonDirection };
