import React from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import { useAccordionContext } from './AccordionItem';

const propTypes = {
  children: PropTypes.node.isRequired,
  /**
   * The component used for the root node.
   * Either a string to use a DOM element or a component.
   */
  tag: PropTypes.elementType,
  defaultClassName: PropTypes.oneOfType([PropTypes.string, PropTypes.arrayOf(PropTypes.string)]),
  className: PropTypes.string,
  onClick: PropTypes.func,
};

const defaultProps = {
  tag: 'div',
  defaultClassName: 'sui-o-accordion__title',
  className: '',
  onClick: () => {},
};

export const AccordionTitle = ({
  tag: Tag,
  defaultClassName,
  className,
  onClick: onClickProp,
  ...attributes
}) => {
  const onToggle = useAccordionContext();

  const onClick = (e) => {
    onToggle(e);

    if (onClickProp) {
      onClickProp();
    }
  };

  const classes = classnames(
    defaultClassName,
    className
  );

  return (
    <Tag onClick={onClick} className={classes} {...attributes} />
  );
};

AccordionTitle.propTypes = propTypes;
AccordionTitle.defaultProps = defaultProps;
