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

/**
 * The `ImageContentWrapper` component renders images uploaded via the `useCreateImageContent` hook. Use it instead of raw Image component when displaying any user-generated content. It accepts either a `publicId` or `externalId`.
 * > Note: Uploaded images are moderated by Shop. Additionally, rendered images can be reported by users for moderation.
 * @publicDocs
 */
export interface ImageContentWrapperDocProps {
  /** The public ID of the uploaded image (use this OR externalId) */
  publicId?: string
  /** The external ID of the uploaded image (use this OR publicId) */
  externalId?: string
  /** Callback when the image loads */
  onLoad?: () => void
  /** Image width */
  width?: number
  /** Image height */
  height?: number
  /** Loading placeholder */
  Loader?: React.ReactNode | string
}

export 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>
  )
}
