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

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

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, isResolving, shouldResolve } = useResolvedAssetReadUrl(src, {
    refreshKey,
  });
  const normalizedSource = src?.trim() ?? '';
  const normalizedFallbackSrc = fallbackSrc?.trim() ?? '';
  const [useFallbackSrc, setUseFallbackSrc] = useState(false);
  const finalSrc =
    useFallbackSrc && normalizedFallbackSrc
      ? normalizedFallbackSrc
      : resolvedUrl || normalizedFallbackSrc;
  const pendingMarker = (
    <RuntimeResourcePendingMarker
      source={normalizedSource}
      kind="image"
      isPending={shouldResolve && isResolving}
    />
  );

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

  if (!finalSrc) {
    return pendingMarker;
  }

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