import React, { useCallback, useMemo, useState } from "react";
import { StyledIconButton, StyledList, StyledListItem, StyledListItemName, StyledSortIcon, StyledSortIconDown, StyledSortIconUp, StyledSortWrapper, StyledValueButton } from "./Styles";
import { Menu } from "../Menu";
export const Sort = _ref => {
  let {
    label,
    icon,
    options,
    selected,
    onChange,
    target,
    className
  } = _ref;
  const [open, setOpen] = useState(false);
  const handleClose = useCallback(() => setOpen(false), []);
  const handleOpen = useCallback(() => setOpen(true), []);
  const handleOnChange = useCallback(event => {
    const nextSortBy = event.currentTarget.dataset.id;
    let nextOrder = selected.sortDirection === "desc" ? "asc" : "desc";
    if (nextSortBy !== selected.sortBy) {
      var _options$find;
      nextOrder = ((_options$find = options.find(opt => opt.id === nextSortBy)) == null ? void 0 : _options$find.defaultDirection) || "asc";
    }
    onChange({
      sortBy: nextSortBy,
      sortDirection: nextOrder
    });
  }, [onChange, selected, options]);
  const labelText = useMemo(() => {
    var _options$find$name, _options$find2;
    return (_options$find$name = (_options$find2 = options.find(opt => opt.id === selected.sortBy)) == null ? void 0 : _options$find2.name) != null ? _options$find$name : "";
  }, [selected.sortBy, options]);
  if (!labelText) {
    console.warn("Cannot find selected id in options.");
  }
  return /*#__PURE__*/React.createElement(Menu, {
    onOpen: handleOpen,
    onClose: handleClose,
    position: "bottom-end",
    target: target || /*#__PURE__*/React.createElement(StyledSortWrapper, {
      className: className
    }, /*#__PURE__*/React.createElement(StyledValueButton, {
      active: open,
      value: labelText,
      label: label,
      "data-testid": "sort-button"
    }), /*#__PURE__*/React.createElement(StyledIconButton, {
      active: open,
      variant: "text gray",
      "data-testid": "sort-icon-button"
    }, icon || /*#__PURE__*/React.createElement(StyledSortIcon, null)))
  }, /*#__PURE__*/React.createElement(StyledList, null, options.map(_ref2 => {
    let {
      id,
      name,
      defaultDirection
    } = _ref2;
    let showDownArrow = selected.sortDirection === "asc";
    if (selected.sortBy !== id) {
      showDownArrow = defaultDirection === "asc";
    }
    return /*#__PURE__*/React.createElement(StyledListItem, {
      key: id,
      onClick: handleOnChange,
      "data-id": id,
      "data-testid": id,
      $active: id === selected.sortBy
    }, /*#__PURE__*/React.createElement(StyledListItemName, null, name), showDownArrow ? /*#__PURE__*/React.createElement(StyledSortIconDown, null) : /*#__PURE__*/React.createElement(StyledSortIconUp, null));
  })));
};
//# sourceMappingURL=Sort.js.map