import { Fragment } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import customizable from "../../../utils/css/customizable.js";
import useRenderedText from './hooks/useRenderedText';
import { MarkdownContext } from './context';
import defaultClasses from './styles.module.scss';

/**
 * Render a string of markdown as HTML with the option of providing your own
 * custom React components in place of the basic HTML tags. This can be useful
 * as a way to render either small snippets of text throughout an app or
 * complete sections of prose.
 *
 * ```js
 *
 * import { MarkdownContent } from '@politico/interactive-style';
 * ```
 */
const MarkdownContent = function MarkdownContent(props) {
  const {
    source,
    components,
    unstyled,
    inline,
    linksExternal,
    tracking
  } = props;
  const content = useRenderedText(source);
  const classes = unstyled ? {} : defaultClasses;
  const Container = inline ? Fragment : 'div';
  const defaultContainerProps = {
    className: classnames(customizable('MarkdownContent'), classes.container)
  };
  const containerProps = inline ? {} : defaultContainerProps;
  return <MarkdownContext.Provider value={{
    components,
    classes,
    inline,
    linksExternal,
    tracking
  }}>
      <Container {...containerProps}>
        {content}
      </Container>
    </MarkdownContext.Provider>;
};
MarkdownContent.defaultProps = {
  source: '',
  components: {},
  unstyled: false,
  inline: false,
  linksExternal: true,
  tracking: {}
};
MarkdownContent.propTypes = {
  /**
   * A string of markdown content to render.
   */
  source: PropTypes.string,
  /**
   * A set of custom components to use to render various pieces of markdown
   * content.
   */
  components: PropTypes.shape({
    'heading-one': PropTypes.elementType,
    'heading-two': PropTypes.elementType,
    'heading-three': PropTypes.elementType,
    'heading-four': PropTypes.elementType,
    'heading-five': PropTypes.elementType,
    'heading-six': PropTypes.elementType,
    paragraph: PropTypes.elementType,
    blockquote: PropTypes.elementType,
    'numbered-list': PropTypes.elementType,
    'bulleted-list': PropTypes.elementType,
    'list-item': PropTypes.elementType,
    rule: PropTypes.elementType,
    image: PropTypes.elementType,
    link: PropTypes.elementType,
    strong: PropTypes.elementType,
    emphasis: PropTypes.elementType,
    code: PropTypes.elementType
  }),
  /**
   * Set to `true` to disable all of the default styling.
   */
  unstyled: PropTypes.bool,
  /**
   * Set to `true` to render inline-only markdown
   */
  inline: PropTypes.bool,
  /**
   * Set to `false` to have links open in the same window
   */
  linksExternal: PropTypes.bool,
  /**
   * Metadata for tracking
   */
  tracking: PropTypes.shape({})
};
export default MarkdownContent;