import React from 'react'
import type {
  ArticleQuery,
  MainImageFragment,
} from '@financial-times/cp-content-pipeline-client'
import ImageSet, { FallbackImage } from '../content-tree/ImageSet/index'
import { ContentTree } from '@financial-times/content-tree'
import type * as ComponentWorkarounds from '../content-tree/Workarounds'
import TopperMainImage from '../Topper/MainImage'

type MainImageProps = {
  content: ArticleQuery['content']
}
const MainImage: React.FC<MainImageProps> = ({ content }) => {
  const references = content.body?.structured.references

  const mainImageTopper =
    content?.topper?.__typename === 'BasicTopper' ||
    content?.topper?.__typename === 'OpinionTopper' ||
    content?.topper?.__typename === 'BrandedTopper'
  /* Main images for articles with simple toppers will be published as lead images in content tree
     If the topper is one of the simple types and contains images, we render them
     using TopperMainImage (which reuses MainImage markup but pulls from topper.images
     instead of body references). This replaces the legacy 'main-image' reference approach. */
  if (
    content.topper &&
    mainImageTopper &&
    'images' in content.topper &&
    Array.isArray(content.topper.images) &&
    content.topper.images.length > 0
  ) {
    return (
      <TopperMainImage
        topper={content.topper}
        hasValidTopperType={mainImageTopper}
      />
    )
  }

  /* Fallback for pre-content tree data where main images are not in the 'images'
    Spark publishes the MainImage at the top of the <body>. if the image is expected to be rendered at all
    We don't want it to appear there, however this is the only way we know whether editorial want to render it.
    So we use the ImageSet from the body to render this above the byline
    Github issue: https://github.com/Financial-Times/content-platform/issues/6
  */

  const mainImage = references?.find(
    (ref): ref is ContentTree.ImageSet & MainImageFragment =>
      ref.type === 'main-image'
  )

  if (mainImage) {
    // CI-3050: remove alt text from main image (DAC recommendation)
    if (mainImage.picture?.alt) {
      mainImage.picture.alt = ''
    }
    return <ImageSet isMainImage content={mainImage} />
  }

  const mainImageRaw = references?.find(
    (ref): ref is ComponentWorkarounds.MainImageRaw =>
      ref.type === 'main-image-raw'
  )

  if (mainImageRaw) {
    // CI-3050: remove alt text from main image (DAC recommendation)
    mainImageRaw.alt = ''
    return <FallbackImage isMainImage content={mainImageRaw} />
  }

  return null
}

export default MainImage
