import React, { useContext } from 'react'
import { BreakpointGetter, FallbackImage, Sources } from '../ImageSet'
import { ScrollyIDContext } from '.'
import { ContentProps } from '../../types'
import type * as ComponentWorkarounds from '../Workarounds'

const scrollyGetBreakpoints: BreakpointGetter = (image) => {
  switch (image.format) {
    case 'desktop':
      return {
        s: { maxWidth: 740, orientation: 'landscape' },
        m: { maxWidth: 980, orientation: 'landscape' },
        l: { maxWidth: 1200, orientation: 'landscape' },
        xl: { maxWidth: 1920, orientation: 'landscape' },
        xxl: { maxWidth: 3840, orientation: 'landscape' },
      }
    case 'mobile':
      return {
        s: { maxWidth: 490, orientation: 'portrait' },
        m: { maxWidth: 600, orientation: 'portrait' },
        l: { maxWidth: 800, orientation: 'portrait' },
        xl: { maxWidth: 1200, orientation: 'portrait' },
        xxl: { maxWidth: 1920, orientation: 'portrait' },
      }
  }
}

interface ScrollyImageProps
  extends ContentProps<ComponentWorkarounds.ScrollyImage> {}

export const ScrollyImage: React.FC<ScrollyImageProps> = ({
  content: { picture },
}) => {
  const scrollyId = useContext(ScrollyIDContext)

  if (!picture?.images) {
    throw new Error(
      `ScrollyImage has no images. Check that they are present in the query`
    )
  }

  return (
    <figure
      className="n-scrollytelling__figure n-content-image--full"
      data-scrollytelling-slide={scrollyId}
    >
      <picture>
        <Sources
          images={picture.images}
          getBreakpoints={scrollyGetBreakpoints}
        />
        <FallbackImage
          content={{ image: picture.fallbackImage }}
          imageType={picture.imageType}
          className="n-scrollytelling__image"
          inSourceSet={true}
        />
      </picture>
      {(picture.caption || picture.credit) && (
        <figcaption className="n-scrollytelling__caption n-scrollytelling__caption--has-caption">
          {picture.caption ? picture.caption + ' ' : ''}
          {picture.credit}
        </figcaption>
      )}
    </figure>
  )
}
