import React, { forwardRef, useState } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import { modifierCSS } from '../../../helpers';

const propTypes = {
  children: PropTypes.node,
  className: PropTypes.string,
  defaultClassName: PropTypes.oneOfType([PropTypes.string, PropTypes.arrayOf(PropTypes.string)]),
  isOpen: PropTypes.bool,
  onToggle: PropTypes.func,
  size: PropTypes.oneOf(['', 'sm', 'lg']),
  /**
   * The component used for the root node.
   * Either a string to use a DOM element or a component.
   */
  tag: PropTypes.elementType,
};

const defaultProps = {
  children: '',
  className: '',
  defaultClassName: 'sui-o-accordion__item',
  isOpen: false,
  onToggle: () => {},
  size: '',
  tag: 'div',
};

export const AccordionContext = React.createContext(() => {});
export const useAccordionContext = () => React.useContext(AccordionContext);

export const AccordionItem = forwardRef(({
  children,
  isOpen: isOpenProp,
  onToggle: onToggleProp,
  tag: Tag,
  defaultClassName,
  className,
  size,
  ...attributes
}, ref) => {
  const [isOpen, setIsOpen] = useState(isOpenProp);

  const onToggle = () => {
    setIsOpen((x) => {
      onToggleProp(!x);
      return !x;
    });
  };

  const classes = classnames(
    defaultClassName,
    className,
    modifierCSS(size),
    {
      'as--open': isOpen,
    },
  );

  return (
    <AccordionContext.Provider value={onToggle}>
      <Tag className={classes} ref={ref} {...attributes}>
        {children}
      </Tag>
    </AccordionContext.Provider>
  );
});

AccordionItem.propTypes = propTypes;
AccordionItem.defaultProps = defaultProps;
