import { type ImgHTMLAttributes, useEffect, useState } from 'react';

import { useResolvedAssetReadUrl } from '../hooks/useResolvedAssetReadUrl';

type ResolvedAssetImageProps = Omit<
  ImgHTMLAttributes<HTMLImageElement>,
  'src'
> & {
  src?: string | null;
  fallbackSrc?: string | null;
  refreshKey?: string | number | null;
};

export function ResolvedAssetImage({
  src,
  fallbackSrc,
  alt,
  refreshKey,
  onError,
  ...rest
}: ResolvedAssetImageProps) {
  const { resolvedUrl } = useResolvedAssetReadUrl(src, {
    refreshKey,
  });
  const normalizedFallbackSrc = fallbackSrc?.trim() ?? '';
  const [useFallbackSrc, setUseFallbackSrc] = useState(false);
  const finalSrc =
    useFallbackSrc && normalizedFallbackSrc
      ? normalizedFallbackSrc
      : resolvedUrl || normalizedFallbackSrc;

  useEffect(() => {
    setUseFallbackSrc(false);
  }, [normalizedFallbackSrc, resolvedUrl]);

  if (!finalSrc) {
    return null;
  }

  return (
    <img
      {...rest}
      src={finalSrc}
      alt={alt}
      onError={(event) => {
        if (
          normalizedFallbackSrc &&
          !useFallbackSrc &&
          finalSrc !== normalizedFallbackSrc
        ) {
          setUseFallbackSrc(true);
        }
        onError?.(event);
      }}
    />
  );
}
