import {ContentWrapper} from '../atoms/content-wrapper'
import {Image} from '../atoms/image'

type ImageContentWrapperProps = (
  | {publicId: string; externalId?: never}
  | {externalId: string; publicId?: never}
) & {
  onLoad?: () => void
  width?: number
  height?: number
  className?: string
  Loader?: React.ReactNode | string
}

export function ImageContentWrapper({
  onLoad,
  width,
  height,
  className,
  publicId,
  externalId,
  Loader,
}: ImageContentWrapperProps) {
  return (
    <ContentWrapper {...(externalId ? {externalId} : {publicId: publicId!})}>
      {({content, loading}) => {
        if (loading) return Loader ? <>{Loader}</> : null

        const aspectRatio =
          content?.image?.width && content?.image?.height
            ? content.image.width / content.image.height
            : undefined

        return (
          <Image
            src={content?.image?.url}
            thumbhash={content?.image?.thumbhash}
            width={width}
            height={height}
            alt={content?.title}
            onLoad={onLoad}
            className={className}
            aspectRatio={aspectRatio}
          />
        )
      }}
    </ContentWrapper>
  )
}
