import PropTypes from 'prop-types';
import React from 'react';

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

/* Interface */
const propTypes = {
  /** Desired aspect ratio. */
  aspectRatio: MediaImagePropTypes.aspectRatio,

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

  /** The post if already available. */
  item: PropTypes.shape({
    featured_media: PropTypes.number,
  }).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,

  /** Width based on img src will be chosen. */
  width: MediaImagePropTypes.width,
};

/**
 * Item featured image
 * Additional props will be passed through to `<MediaImage>`.
 * @param {Object} props - React component props.
 * @returns {Object} React element.
 */
export const ItemFeaturedImage = ({
  item: { featured_media: mediaId },
  ...passThroughProps
}) => {
  if (!mediaId) {
    return null;
  }

  return (
    <MediaImage id={ mediaId } { ...passThroughProps } />
  );
};

ItemFeaturedImage.propTypes = propTypes;

export default createItemComponent(['placeholder'])(ItemFeaturedImage);
