import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
import _toConsumableArray from "@babel/runtime/helpers/esm/toConsumableArray";

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }

// eslint-disable-next-line import/no-duplicates
import * as React from 'react';
import { createContext, useReducer, useEffect, useRef, useCallback, useMemo, useState // eslint-disable-next-line import/no-duplicates
} from 'react';
import cx from 'classnames';
import useReducedMotion from '../utils/useReducedMotion';
import { __DEV__, invariant } from '../utils';
import { generateResponsiveClassNames } from '../utils/responsive-props';
export var KEY_CODES = {
  '32': 'space',
  '13': 'enter'
};
export var AccordionContext = /*#__PURE__*/createContext({});

var Accordion = function Accordion(_ref) {
  var children = _ref.children,
      _ref$allowMultiple = _ref.allowMultiple,
      allowMultiple = _ref$allowMultiple === void 0 ? false : _ref$allowMultiple,
      _ref$className = _ref.className,
      className = _ref$className === void 0 ? '' : _ref$className,
      _ref$spacing = _ref.spacing,
      spacing = _ref$spacing === void 0 ? 's' : _ref$spacing,
      _ref$reduceMotion = _ref.reduceMotion,
      reduceMotion = _ref$reduceMotion === void 0 ? false : _ref$reduceMotion,
      defaultExpanded = _ref.defaultExpanded,
      expanded = _ref.expanded,
      onChange = _ref.onChange,
      ariaLabel = _ref['aria-label'],
      ariaLabelledby = _ref['aria-labelledby'];
  var wrapperRef = useRef(null);
  var isControlled = expanded !== undefined;

  var _useRef = useRef(isControlled),
      wasControlled = _useRef.current;

  if (__DEV__) {
    invariant(!(isControlled && !onChange), // eslint-disable-next-line max-len
    'You provided an `expanded` prop to an Accordion without an `onChange` handler. Users won`t be able to switch between expanded/collapsed state.');
    invariant(!(wasControlled && !isControlled), 'You cannot change Accordion component from controlled to uncontrolled variant.');
    invariant(!(!wasControlled && isControlled), 'You cannot change Accordion component from uncontrolled to controlled variant.');
    invariant(!(isControlled && allowMultiple), 'allowMultiple is not working in controlled Accordion');
    invariant(!(!allowMultiple && Array.isArray(defaultExpanded) && defaultExpanded.length > 1), // eslint-disable-next-line max-len
    'defaultExpanded is an array with more than 1 element but allowMultiple prop is not set. The first value from the array was picked as a default expanded. Set allowMultiple attribute or provide only one default expanded.');
  }

  var getUpdatedOpenedItems = useCallback(function (expanded, id, value) {
    if (value) {
      return allowMultiple ? _toConsumableArray(new Set([].concat(_toConsumableArray(expanded), [id]))) : [id];
    }

    return allowMultiple ? expanded.filter(function (item) {
      return item !== id;
    }) : [];
  }, [allowMultiple]);

  var _useReducer = useReducer(reducer, null, function () {
    if (isControlled) {
      return {
        expanded: [],
        focusedElementId: null
      };
    }

    if (defaultExpanded !== undefined) {
      var expandedArray = Array.isArray(defaultExpanded) ? defaultExpanded : [defaultExpanded];
      var newState = expandedArray.filter(function (item, idx) {
        return allowMultiple || idx < 1;
      });
      return {
        expanded: newState,
        focusedElementId: null
      };
    }

    return {
      expanded: [],
      focusedElementId: null
    };
  }),
      _useReducer2 = _slicedToArray(_useReducer, 2),
      state = _useReducer2[0],
      dispatch = _useReducer2[1];

  var hasReduceMotion = useReducedMotion() || reduceMotion;
  useEffect(function () {
    var wrapper = wrapperRef.current;

    function handleKeyDown(event) {
      var key = KEY_CODES[event.keyCode];

      if (['space', 'enter'].includes(key)) {
        if (event.target instanceof HTMLElement && event.target.id === state.focusedElementId) {
          event.preventDefault();
        }

        dispatch({
          type: 'accordion/KEYBOARD_SET_EXPANDED'
        });
      }
    }

    if (!wrapper) return;
    wrapper.addEventListener('keydown', handleKeyDown);
    return function () {
      if (!wrapper) return;
      wrapper.removeEventListener('keydown', handleKeyDown);
    };
  }, [state.focusedElementId]);

  function reducer(state, action) {
    switch (action.type) {
      case 'accordion/TOGGLE_EXPAND':
        {
          var _action$payload = action.payload,
              _id = _action$payload.id,
              _expanded = _action$payload.expanded;
          return _objectSpread(_objectSpread({}, state), {}, {
            expanded: getUpdatedOpenedItems(state.expanded, _id, _expanded)
          });
        }

      case 'accordion/SET_EXPANDED':
        {
          var _expanded2 = action.payload.expanded;
          return _objectSpread(_objectSpread({}, state), {}, {
            expanded: _expanded2
          });
        }

      case 'accordion/KEYBOARD_SET_EXPANDED':
        {
          var _expanded3 = state.expanded,
              focusedElementId = state.focusedElementId;
          if (focusedElementId === null) return state;
          return _objectSpread(_objectSpread({}, state), {}, {
            expanded: getUpdatedOpenedItems(state.expanded, focusedElementId, !_expanded3.includes(focusedElementId))
          });
        }

      case 'accordion/SET_FOCUSED':
        {
          return _objectSpread(_objectSpread({}, state), {}, {
            focusedElementId: action.payload.id
          });
        }

      default:
        return state;
    }
  }

  var _useState = useState(''),
      _useState2 = _slicedToArray(_useState, 2),
      prevExpanded = _useState2[0],
      setPrevExpanded = _useState2[1];

  if (isControlled && expanded !== prevExpanded) {
    setPrevExpanded(expanded); // expanded || '' is to satisfy flow.
    // isControlled flag is true when expanded !== undefined but this condition is not interpreted
    // correctly by flow causing type error. Replacing isControlled with expanded !== undefined would work but using isControlled is more clear

    var expandedArray = Array.isArray(expanded) ? expanded : [expanded || ''];
    dispatch({
      type: 'accordion/SET_EXPANDED',
      payload: {
        expanded: expandedArray
      }
    });
  }

  var noGapBetweenElements = spacing === 'none';
  var onItemSelect = useCallback(function (id, value) {
    onChange && onChange(id);

    if (!isControlled) {
      dispatch({
        type: 'accordion/TOGGLE_EXPAND',
        payload: {
          id: id,
          expanded: value
        }
      });
    }
  }, [isControlled, onChange]);
  var context = useMemo(function () {
    return {
      noGapBetweenElements: noGapBetweenElements,
      expanded: state.expanded,
      focusedElementId: state.focusedElementId,
      dispatch: dispatch,
      reduceMotion: hasReduceMotion,
      onItemSelect: onItemSelect
    };
  }, [hasReduceMotion, noGapBetweenElements, onItemSelect, state.focusedElementId, state.expanded]);
  return /*#__PURE__*/React.createElement(AccordionContext.Provider, {
    value: context
  }, /*#__PURE__*/React.createElement("div", {
    ref: wrapperRef,
    className: cx.apply(void 0, _toConsumableArray(generateResponsiveClassNames(function (spacing) {
      return "sg-space-y-".concat(String(spacing));
    }, spacing)).concat([className])),
    "aria-label": ariaLabel,
    "aria-labelledby": ariaLabelledby
  }, children));
};

export default Accordion;