import { PictureOutlined } from '@ant-design/icons';
import type { ImgHTMLAttributes } from 'react';
import { useEffect, useState } from 'react';

type InlineImageProps = ImgHTMLAttributes<HTMLImageElement> & {
  fallbackText?: string;
};

export function InlineImage({ alt, className, fallbackText, onError, src, ...rest }: InlineImageProps) {
  const [hasError, setHasError] = useState(!src);

  useEffect(() => {
    setHasError(!src);
  }, [src]);

  if (hasError) {
    return (
      <div
        className={['inline-image-fallback', className].filter(Boolean).join(' ')}
        role="img"
        aria-label={alt || fallbackText || '이미지를 불러오지 못했습니다.'}
      >
        <PictureOutlined />
        <span>{fallbackText || '이미지를 불러오지 못했습니다.'}</span>
      </div>
    );
  }

  return (
    <img
      {...rest}
      alt={alt}
      className={className}
      src={src}
      onError={(event) => {
        setHasError(true);
        onError?.(event);
      }}
    />
  );
}
