"use client";

import { ImageProps } from "next/image";
import { useState } from "react";

type CustomImageProps = Omit<ImageProps, "src"> & {
  src?: string | null;
  fallbackSrc?: string;
};

const DEFAULT_FALLBACK = "/images/default_credit_usage_image.png";

export default function CustomImage({
  src,
  fallbackSrc = DEFAULT_FALLBACK,
  alt = "",
  onError,
  ...props
}: CustomImageProps) {
  const [imageSrc, setImageSrc] = useState<string>(src || fallbackSrc);

  const handleError = (event: React.SyntheticEvent<HTMLImageElement>) => {
    // Don't keep trying the fallback if the fallback itself fails
    if (imageSrc !== fallbackSrc) {
      setImageSrc(fallbackSrc);
    }

    onError?.(event);
  };

  return <img {...props} src={imageSrc} alt={alt} onError={handleError} />;
}
