import { Container, clx } from "@medusajs/ui"
import Image from "next/image"
import React from "react"

import PlaceholderImage from "@modules/common/icons/placeholder-image"

type ThumbnailProps = {
  thumbnail?: string | null
  // TODO: Fix image typings
  images?: any[] | null
  size?: "small" | "medium" | "large" | "full" | "square"
  isFeatured?: boolean
  className?: string
  "data-testid"?: string
}

const VtThumbnail: React.FC<ThumbnailProps> = ({
  thumbnail,
  images,
  size = "small",
  isFeatured,
  className,
  "data-testid": dataTestid,
}) => {
  const imageUrls = images?.map((i: any) => i.url) || []
  const initialImage = thumbnail || imageUrls?.[0]

  let hoverImage: string | undefined = initialImage
  if (imageUrls.length > 1) {
     hoverImage = imageUrls.find((u) => u !== initialImage)
  }

  return (
    <Container
      className={clx(
        "group relative w-full overflow-hidden p-4 bg-ui-bg-subtle shadow-elevation-card-rest group-hover:shadow-elevation-card-hover transition-shadow ease-in-out duration-150",
        className,
        {
          "aspect-[11/14]": isFeatured,
          "aspect-[9/16]": !isFeatured && size !== "square",
          "aspect-[1/1]": size === "square",
          "w-[180px]": size === "small",
          "w-[290px]": size === "medium",
          "w-[440px]": size === "large",
          "w-full": size === "full",
        }
      )}
      data-testid={dataTestid}
    >
      <ImageOrPlaceholder
        image={initialImage}
        size={size}
        className="opacity-100 group-hover:opacity-0 transition-opacity duration-300"
      />
      {hoverImage && (
        <ImageOrPlaceholder
          image={hoverImage}
          size={size}
          className="opacity-0 group-hover:opacity-100 transition-opacity duration-300"
        />
      )}
    </Container>
  )
}

const ImageOrPlaceholder = ({
  image,
  size,
  className,
}: Pick<ThumbnailProps, "size"> & { image?: string; className?: string }) => {
  return image ? (
    <Image
      src={image}
      alt="Thumbnail"
      className={clx("absolute inset-0 object-cover object-center", className)}
      draggable={false}
      quality={50}
      sizes="(max-width: 576px) 280px, (max-width: 768px) 360px, (max-width: 992px) 480px, 800px"
      fill
    />
  ) : (
    <div className={clx("w-full h-full absolute inset-0 flex items-center justify-center", className)}>
      <PlaceholderImage size={size === "small" ? 16 : 24} />
    </div>
  )
}

export default VtThumbnail
