import { WOSA_BASE_URL } from '@/config/site-config';
import { useEffect, useState } from 'react';
import CommonImage from './CommonImage';
import { ImgHTMLAttributes } from 'react';

export interface AsyncImageProps extends ImgHTMLAttributes<HTMLImageElement> {
  src: string; // image file name (required)
  fallback: string; // fallback image if src not found (required)
  directory?: string; // optional directory
  classname?: string; // optional CSS class
  alt?: string; // optional alt text
  width?: number; // optional width
  height?: number; // optional height
}

export const fetchImage = async (
  image: string,
  directoryName?: string,
): Promise<string> => {
  if (!image) return `/header/no-image.png`;

  const url = directoryName
    ? `${WOSA_BASE_URL}uploads/${directoryName}/${image}`
    : `${WOSA_BASE_URL}uploads/${image}`;

  try {
    const exists = await checkImageExists(url);
    return exists ? url : `/header/no-image.png`;
  } catch {
    return `/header/no-image.png`;
  }
};

const checkImageExists = (url: string): Promise<boolean> => {
  return new Promise((resolve) => {
    const img = new Image();
    img.onload = () => resolve(true);
    img.onerror = () => resolve(false);
    img.src = url;
  });
};

const AsyncImage: React.FC<AsyncImageProps> = ({
  src,
  fallback,
  directory,
  classname = '',
  alt = '',
  width = 100,
  height = 100,
  ...props
}) => {
  const [imgSrc, setImgSrc] = useState(fallback);

  useEffect(() => {
    const loadImage = async () => {
      if (!src) return setImgSrc(fallback);

      const url = directory
        ? `${WOSA_BASE_URL}uploads/${directory}/${src}`
        : `${WOSA_BASE_URL}uploads/${src}`;

      try {
        const exists = await checkImageExists(url);
        setImgSrc(exists ? url : fallback);
      } catch {
        setImgSrc(fallback);
      }
    };

    loadImage();
  }, [src, fallback, directory]);

  return (
    <CommonImage
      src={imgSrc}
      alt={alt}
      width={width}
      height={height}
      classname={classname}
      {...props}
    />
  );
};

export default AsyncImage;
