import React from 'react';
import composeClassName from './classNames';

const PanelHeader = ({
  className = '',
  leading = null,
  title = null,
  titleTag = 'h2',
  titleProps = {},
  actions = null,
}) => {
  const headerClassName = composeClassName('panel-header', className);

  const renderTitle = () => {
    if (title == null) {
      return null;
    }

    if (React.isValidElement(title)) {
      if (title.type === React.Fragment) {
        return (
          <span className="panel-header__title" {...titleProps}>
            {title}
          </span>
        );
      }

      const mergedClassName = composeClassName('panel-header__title', title.props.className || '');
      return React.cloneElement(title, {
        ...titleProps,
        className: mergedClassName,
      });
    }

    const HeadingTag = titleTag;
    return (
      <HeadingTag className="panel-header__title" {...titleProps}>
        {title}
      </HeadingTag>
    );
  };

  return (
    <div className={headerClassName}>
      {leading ? <div className="panel-header__leading">{leading}</div> : null}
      {renderTitle()}
      {actions ? <div className="panel-header__actions">{actions}</div> : null}
    </div>
  );
};

export default PanelHeader;
