/**
 * Copyright (c) OpenLens Authors. All rights reserved.
 * Licensed under MIT License. See LICENSE in root directory for more information.
 */

import styles from "./icon.module.css";

import { cssNames } from "@k8slens/utilities";
import React, { useState } from "react";

export interface HelmChartIconProps {
  className?: string;
  imageUrl?: string;
}

export const HelmChartIcon = ({
  imageUrl = "",
  className,
}: HelmChartIconProps) => {
  const [isImageLoaded, setIsImageLoaded] = useState(false);
  const backgroundImage = `url(${imageUrl})`;
  const placeholderImageUrl = "data:image/svg+xml;base64,[encoded data, 5168 characters]";

  const handleImageLoad = () => {
    setIsImageLoaded(true);
  };

  const isValidImage = () => {
    return /^https?:\/\/.*(?<!\.svg)$/.test(imageUrl);
  };

  return (
    <div
      className={cssNames(styles.chartIcon, className, { [styles.imageNotLoaded]: !isImageLoaded })}
      data-testid="image-container"
      style={{
        backgroundImage: isImageLoaded ? backgroundImage : `url(${placeholderImageUrl})`,
      }}
    >
      {isValidImage() && (
        <img
          className={styles.img}
          src={imageUrl}
          alt=""
          onLoad={handleImageLoad}
        />
      )}
    </div>
  );
};
