import React from 'react'
import classnames from 'classnames'
import { ContentProps } from '../../types'
import Message from '../../Message'
import { ContentTree } from '@financial-times/content-tree'
import ContentTreeFull = ContentTree.full

interface FlourishProps extends ContentProps<ContentTreeFull.Flourish> {
  iFrame?: boolean
  inArticleBody?: boolean
}

const Flourish: React.FC<FlourishProps> = ({
  content: {
    id,
    flourishType,
    description,
    layoutWidth,
    fallbackImage,
    fragmentIdentifier,
  },
  iFrame = false,
  inArticleBody = true,
}) => {
  if (!id) return null
  const anchorHref = `#${id}`
  const fullGrid = layoutWidth === 'full-grid'
  const figureClassnames = classnames({
    'n-content-picture': true,
    'n-content-layout__container': true,
    'n-content-picture--wide': fullGrid,
    flourish__figure: iFrame,
  })

  const iframeAspectRatio =
    iFrame && fallbackImage?.width && fallbackImage?.height
      ? `${fallbackImage.width}/${fallbackImage.height}`
      : '16/9'

  const imageAspectRatio =
    !inArticleBody && fallbackImage?.width && fallbackImage?.height
      ? {
          width: '100%',
          aspectRatio: `${fallbackImage.width}/${fallbackImage.height}`,
        }
      : {}

  return (
    <div
      id={fragmentIdentifier}
      className={classnames({
        'n-content-layout': inArticleBody,
        'flourish--topper': !inArticleBody,
        flourish: iFrame,
        'flourish--iFrame': iFrame,
      })}
      data-layout-width={fullGrid ? 'full-grid' : null}
      data-component="flourish"
      data-component-id={id}
      data-component-type={
        inArticleBody ? 'flourish-in-article' : 'flourish-topper'
      }
    >
      {iFrame && (
        <iframe
          src={`https://flo.uri.sh/visualisation/${id}/embed?hideTitle=${!inArticleBody}`} // hide the title of if in topper
          style={{ width: '100%', aspectRatio: iframeAspectRatio }}
          className="flourish__i-frame"
        ></iframe>
      )}
      <figure
        className={figureClassnames}
        data-original-image-width={fullGrid ? fallbackImage?.width : null}
        data-original-image-height={fullGrid ? fallbackImage?.height : null}
      >
        <a href={anchorHref}>
          <picture
            // `flourish-embed` loads an iframe containing the JS version of a flourish chart
            // `flourish` will be instead targeted by the flourish JS, that will replace the picture with the flourish JS version contained in an iframe
            data-asset-type={iFrame ? 'flourish-embed' : 'flourish'}
            data-flourish-id={id}
            data-flourish-type={flourishType}
          >
            <Message id={id} type="notice" state="inform" />
            <img
              src={fallbackImage?.url || ''}
              alt={description}
              style={imageAspectRatio}
            />
          </picture>
        </a>
      </figure>
    </div>
  )
}

export default Flourish
