import PropTypes from 'prop-types';
import React from 'react';
import { Header } from 'semantic-ui-react';

import createItemComponent, {
  propTypes as ItemPropTypes,
} from './createItemComponent';

/* Interface */
const propTypes = {
  /** An element type to render as (string or function). */
  as: PropTypes.oneOfType([
    PropTypes.func.isRequired,
    PropTypes.string.isRequired,
  ]),

  /** Additional suffix to append after the title. */
  children: PropTypes.element,

  /** ID of post to load. */
  id: ItemPropTypes.id,

  /** The post if already available. */
  item: PropTypes.shape({
    title: PropTypes.shape({
      rendered: PropTypes.string.isRequired,
    }),
  }).isRequired,

  /** Slug of post to load. */
  itemSlug: ItemPropTypes.itemSlug,

  /** Content to display while awaiting data. */
  placeholder: ItemPropTypes.placeholder,

  /** Slug for post type from which posts are drawn. */
  typeSlug: ItemPropTypes.typeSlug,
};

/* Defaults */
const defaultProps = {
  as: Header,
};

/**
 * Item title
 * Additional props will be passed through to SUI's `<Header>` or the component
 * specified by the `as` prop.
 * @param {Object} props - React component props.
 * @returns {Object} React element.
 */
export const ItemTitle = ({
  as: Component,
  children,
  item: { title },
  ...passThroughProps
}) => {
  if (!title) {
    return null;
  }

  return (
    <Component { ...passThroughProps }>
      <span dangerouslySetInnerHTML={ { __html: title.rendered } } />
      { children }
    </Component>
  );
};

ItemTitle.propTypes = propTypes;
ItemTitle.defaultProps = defaultProps;

export default createItemComponent()(ItemTitle);
