import React, { useState, useEffect } from "react";
import { ImageBaseURL } from "../api/utils/config";

interface ImageProps extends React.ImgHTMLAttributes<HTMLImageElement> {
  src: string;
}

const CustomImage: React.FC<ImageProps> = ({ src, ...props }) => {
  const addBaseUrlToSrc = (src: string) => {
    return ImageBaseURL + src?.replace("public", "/storage");
  };

  const [imgSrc, setImgSrc] = useState(addBaseUrlToSrc(src));

  useEffect(() => {
    setImgSrc(addBaseUrlToSrc(src));
  }, [src]);

  const handleError = () => {
    setImgSrc("/Home/p1.png");
  };

  return (
    <img
      src={imgSrc}
      onError={handleError}
      {...props}
      alt={props.alt || "image"}
    />
  );
};

export default CustomImage;
