import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
// eslint-disable-next-line import/no-duplicates
import * as React from 'react'; // eslint-disable-next-line import/no-duplicates

import { useContext, useEffect, useRef, useState } from 'react';
import { generateId } from '../utils';
import cx from 'classnames';
import Box from '../box/Box';
import Flex from '../flex/Flex';
import Icon, { ICON_COLOR } from '../icons/Icon';
import Link from '../text/Link';
import Text from '../text/Text';
import { AccordionContext } from './Accordion';

var AccordionItem = function AccordionItem(_ref) {
  var title = _ref.title,
      _ref$titleSize = _ref.titleSize,
      titleSize = _ref$titleSize === void 0 ? 'large' : _ref$titleSize,
      children = _ref.children,
      _ref$className = _ref.className,
      className = _ref$className === void 0 ? '' : _ref$className,
      _ref$padding = _ref.padding,
      padding = _ref$padding === void 0 ? 'm' : _ref$padding,
      _ref$tabIndex = _ref.tabIndex,
      tabIndex = _ref$tabIndex === void 0 ? 0 : _ref$tabIndex,
      customId = _ref.id,
      _ref$ariaHeadingLevel = _ref.ariaHeadingLevel,
      ariaHeadingLevel = _ref$ariaHeadingLevel === void 0 ? 2 : _ref$ariaHeadingLevel;
  var contentRef = useRef(null);

  var _useRef = useRef(customId !== null && customId !== void 0 ? customId : "AccordionItem_".concat(generateId())),
      id = _useRef.current;

  var contentId = "Section_".concat(id);

  var _useContext = useContext(AccordionContext),
      noGapBetweenElements = _useContext.noGapBetweenElements,
      expanded = _useContext.expanded,
      focusedElementId = _useContext.focusedElementId,
      dispatch = _useContext.dispatch,
      reduceMotion = _useContext.reduceMotion,
      onItemSelect = _useContext.onItemSelect;

  var hasRenderedInitially = useRef(false);

  var _useState = useState(false),
      _useState2 = _slicedToArray(_useState, 2),
      isHovered = _useState2[0],
      setIsHovered = _useState2[1];

  var isCollapsed = !expanded.includes(id);
  var isFocused = focusedElementId === id;
  var isHighlighted = isHovered || isFocused;
  var isBorderHighlighted = isHighlighted && !noGapBetweenElements;
  var isTitleString = typeof title === 'string';
  var toggleOpen = React.useCallback(function () {
    onItemSelect(id, isCollapsed);
  }, [id, isCollapsed, onItemSelect]);
  var handleFocus = React.useCallback(function () {
    dispatch({
      type: 'accordion/SET_FOCUSED',
      payload: {
        id: id
      }
    });
  }, [dispatch, id]);
  var handleBlur = React.useCallback(function () {
    dispatch({
      type: 'accordion/SET_FOCUSED',
      payload: {
        id: ''
      }
    });
  }, [dispatch]);
  useEffect(function () {
    var content = contentRef.current;

    function collapse() {
      if (!contentRef.current) {
        return;
      }

      if (reduceMotion || !hasRenderedInitially.current) {
        contentRef.current.style.height = "".concat(0, "px");
        contentRef.current.hidden = true;
        contentRef.current.style.overflow = 'hidden';
        hasRenderedInitially.current = true;
      } else {
        var sectionHeight = contentRef.current.scrollHeight;
        requestAnimationFrame(function () {
          if (!contentRef.current) {
            return;
          }

          contentRef.current.style.height = "".concat(sectionHeight, "px");
          requestAnimationFrame(function () {
            if (!contentRef.current) {
              return;
            }

            contentRef.current.style.height = "0px";
            contentRef.current.style.overflow = "hidden";
            contentRef.current.addEventListener('transitionend', onTransitionEnd);
          });
        });
      }
    }

    function expand() {
      if (!contentRef.current) {
        return;
      }

      contentRef.current.hidden = false;
      var sectionHeight = contentRef.current.scrollHeight;

      if (reduceMotion || !hasRenderedInitially.current) {
        contentRef.current.style.height = 'auto';
        contentRef.current.style.overflow = 'visible';
        hasRenderedInitially.current = true;
      } else {
        contentRef.current.style.height = "".concat(sectionHeight, "px");
        contentRef.current.addEventListener('transitionend', onTransitionEnd);
      }
    }

    function onTransitionEnd() {
      if (!contentRef.current) {
        return;
      }

      if (contentRef.current.style.height === '0px') {
        // we set hidden in order to prevent gaining focus inside collapsed content
        contentRef.current.hidden = true;
      } else {
        contentRef.current.style.height = 'auto';
        contentRef.current.style.overflow = 'visible';
      }

      contentRef.current.removeEventListener('transitionend', onTransitionEnd);
    }

    isCollapsed ? collapse() : expand();
    return function () {
      if (!content) {
        return;
      }

      content.removeEventListener('transitionend', onTransitionEnd);
    };
  }, [isCollapsed, reduceMotion]);
  return React.useMemo(function () {
    return /*#__PURE__*/React.createElement(Box, {
      color: "white",
      border: true,
      borderColor: isBorderHighlighted ? 'gray-40' : 'gray-20',
      className: cx('sg-accordion-item', {
        'sg-accordion-item--no-gap': noGapBetweenElements,
        'sg-accordion-item--reduced-motion': reduceMotion
      }, className),
      padding: null
    }, /*#__PURE__*/React.createElement("div", {
      role: "heading",
      "aria-level": ariaHeadingLevel,
      id: id
    }, /*#__PURE__*/React.createElement(Box, {
      padding: padding,
      className: "sg-accordion-item__button",
      onClick: toggleOpen,
      onMouseEnter: function onMouseEnter() {
        return setIsHovered(true);
      },
      onMouseLeave: function onMouseLeave() {
        return setIsHovered(false);
      },
      onFocus: handleFocus,
      onBlur: handleBlur,
      "aria-expanded": !isCollapsed,
      "aria-controls": contentId,
      role: "button",
      tabIndex: tabIndex
    }, /*#__PURE__*/React.createElement(Flex, {
      direction: "row",
      justifyContent: "space-between",
      alignItems: "center"
    }, isTitleString ? /*#__PURE__*/React.createElement(Link, {
      size: titleSize,
      color: "text-black",
      weight: "bold",
      underlined: isHighlighted,
      disabled: true
    }, title) : /*#__PURE__*/React.createElement("span", {
      className: "sg-accordion-item__title"
    }, title), /*#__PURE__*/React.createElement(Flex, {
      justifyContent: "center",
      alignItems: "center",
      className: cx('sg-accordion-item__icon', {
        'sg-accordion-item__icon--hover': isHighlighted
      })
    }, /*#__PURE__*/React.createElement(Icon, {
      type: "chevron_down",
      color: ICON_COLOR['icon-black'],
      className: cx('sg-accordion-item__arrow', {
        'sg-accordion-item__arrow--visible': !isCollapsed
      }),
      "aria-hidden": "true"
    }))))), /*#__PURE__*/React.createElement("div", {
      ref: contentRef,
      className: "sg-accordion-item__content",
      id: contentId,
      role: "region",
      "aria-labelledby": id,
      hidden: true
    }, /*#__PURE__*/React.createElement(Box, {
      padding: padding,
      className: "sg-accordion-item__content-box"
    }, /*#__PURE__*/React.createElement(Text, null, children))));
  }, [isBorderHighlighted, noGapBetweenElements, ariaHeadingLevel, children, className, contentId, handleBlur, handleFocus, id, isCollapsed, isHighlighted, isTitleString, padding, reduceMotion, tabIndex, title, titleSize, toggleOpen]);
};

export default AccordionItem;