import React from 'react';
import PropTypes from 'prop-types';
import cx from 'classnames';
import { Transformer, interpolate } from '@moonwalker/lifesupport';

import { Picture } from '../picture';
import css from './dynamic-content.module.css';

const PICTURE_DEFAULT_WIDTH = '200';
const IMG_LOADING = ['auto', 'eager', 'lazy'];

const TransformPicture = ({ width = PICTURE_DEFAULT_WIDTH, src, align, alt, title, loading }) => {
  let transformW = 0;

  // Typecast width attribute
  try {
    transformW = parseInt(width, 10);
  } catch (err) {
    // skip
  }

  return (
    <Picture
      image={{ file: { url: src } }}
      transform={{ w: transformW }}
      align={align}
      alt={alt}
      title={title}
      loading={loading}
      webp
    />
  );
};

TransformPicture.propTypes = {
  width: PropTypes.string,
  src: PropTypes.string.isRequired,
  align: PropTypes.string,
  alt: PropTypes.string,
  title: PropTypes.string,
  loading: PropTypes.oneOf(IMG_LOADING).isRequired
};

TransformPicture.defaultProps = {
  width: PICTURE_DEFAULT_WIDTH,
  align: '',
  alt: '',
  title: ''
};

const getTransformPicture = ({ loading }) => {
  const TransformPictureWithContext = (props) => <TransformPicture {...props} loading={loading} />;

  return TransformPictureWithContext;
};

/**
 * DynamicContent component
 *
 * MDX enabled transformer with custom content components(a, Picture, img)
 *
 * @param {import('types').IDynamicContentProps} props
 * @return {React.ReactElement}
 */
export const DynamicContent = (props) => {
  const { as: Component, className, children, args, components, loading } = props;

  const normalizedSource = args ? interpolate(children, args) : children;

  const normalizedComponents = {
    img: getTransformPicture({ loading }),
    Picture: getTransformPicture({ loading }),
    ...components
  };

  return (
    <Component className={cx(css.root, className)}>
      <Transformer source={normalizedSource} components={normalizedComponents} />
    </Component>
  );
};

DynamicContent.defaultProps = {
  className: '',
  as: 'div',
  args: null,
  components: null,
  loading: 'auto'
};

DynamicContent.propTypes = {
  /** Adopted child class name */
  className: PropTypes.string,

  /** Render as component */
  as: PropTypes.elementType,

  /** Content to transform */
  children: PropTypes.string.isRequired,

  /** Introspection arguments */
  args: PropTypes.object, // eslint-disable-line react/forbid-prop-types

  /** Transformer components */
  components: PropTypes.object, // eslint-disable-line react/forbid-prop-types

  /** IMG & Iframes loading attr */
  loading: PropTypes.oneOf(IMG_LOADING)
};
