import type { JSX } from "react"

export interface PicturePresetProps extends Omit<NativeImgProps, "src"> {
  avif?: NativeSource
  webp?: NativeSource
  src: string
  fetchpriority?: "low" | "high"
  importance?: "low" | "high"
  useProxy?: boolean
  imageWidth?: number | string
  imageHeight?: number | string
  host?: string
  proxyHost?: string
}

export const PicturePreset = ({
  src,
  avif,
  webp,
  width,
  imageWidth = "100%",
  imageHeight = "100%",
  height,
  decoding = "async",
  loading = "lazy",
  fetchpriority = "low",
  importance = "low",
  alt,
  useProxy,
  host,
  proxyHost,
  ...props
}: PicturePresetProps): JSX.Element => {
  const imagePath = (format: string) => {
    if (useProxy) {
      return `${proxyHost}/${src}?format=${format}`
    }
    return `${host}${src}?format=${format}`
  }

  return (
    <picture>
      <source srcSet={imagePath("avif")} {...avif} type="image/avif" />
      <source srcSet={imagePath("webp")} {...webp} type="image/webp" />
      <img
        loading={loading}
        src={src}
        alt={alt}
        aria-label={alt}
        // @ts-expect-error - TS doesn't know about these attributes
        fetchpriority={fetchpriority}
        importance={fetchpriority}
        width={imageWidth}
        height={imageHeight}
        decoding={decoding}
        {...props}
      />
    </picture>
  )
}

type NativeImgProps = React.DetailedHTMLProps<
  React.ImgHTMLAttributes<HTMLImageElement>,
  HTMLImageElement
>

type NativeSource = React.DetailedHTMLProps<
  React.SourceHTMLAttributes<HTMLSourceElement>,
  HTMLSourceElement
>
