import { Box, BoxProps, Image, SystemStyleObject } from '@chakra-ui/react'

type ResponsiveImageProps = {
  url: string | null
  avatar?: boolean
  alt: string
  imageStyle?: SystemStyleObject
  filter?: string
}

// const defaultSizes = 'sizes[]=300,sizes[]=600,sizes[]=900,sizes[]=1200,sizes[]=1800'

const ResponsiveImage: React.FC<ResponsiveImageProps & BoxProps> = ({
  url,
  avatar,
  alt,
  children,
  imageStyle,
  w,
  h,
  ...rest
}) => {
  if (url === null) return null

  let placeholder
  let responsiveImage
  let responsiveImageWebp

  // The sizes are hardcoded because of a bug with webpack that impedes parametrization string interpolation
  // after the question mark
  // see https://github.com/cyrilwanner/next-optimized-images/issues/16
  if (avatar) {
    placeholder = require(`../assets/${url}?lqip`)
    responsiveImage = require(`../assets/${url}?resize&sizes[]=96,sizes[]=128,sizes[]=256&format=jpg`)
    responsiveImageWebp = require(`../assets/${url}?resize&sizes[]=96,sizes[]=128,sizes[]=256&format=webp`)
  } else {
    placeholder = require(`../assets/${url}?lqip`)
    responsiveImage = require(`../assets/${url}?resize&sizes[]=300,sizes[]=600,sizes[]=900,sizes[]=1200,sizes[]=1800&sizes[]=1900&quality=85format=jpg`)
    responsiveImageWebp = require(`../assets/${url}?resize&sizes[]=300,sizes[]=600,sizes[]=900,sizes[]=1200,sizes[]=1800,sizes[]=1900&quality=90&format=webp`)
  }

  const src = responsiveImage.src.replaceAll('_next', '/_next')
  const srcSet = responsiveImage.srcSet.replaceAll('_next', '/_next')
  const srcSetWebp = responsiveImageWebp.srcSet.replaceAll('_next', '/_next')

  return (
    <Box
      width={w ?? responsiveImage.width}
      height={h ?? responsiveImage.height}
      background={`url(${placeholder})`}
      backgroundSize="cover"
      position="relative"
      overflow="hidden"
      sx={{
        '& picture img': imageStyle,
      }}
      {...rest}
    >
      {children}
      <picture>
        <source srcSet={srcSetWebp} type="image/webp" />
        <Image
          objectFit="cover"
          objectPosition="center"
          w="100%"
          h="100%"
          alt={alt}
          src={src}
          srcSet={srcSet}
          loading="lazy"
        />
      </picture>
    </Box>
  )
}

export default ResponsiveImage
