import { useState, useEffect } from 'react';
import { getProxiedImageUrl } from '../../utils/images';

interface ProxiedImageProps {
  src: string | undefined | null;
  alt: string;
  className?: string;
  style?: React.CSSProperties;
  fallback?: React.ReactNode;
  onError?: () => void;
  onLoad?: () => void;
}

export function ProxiedImage({ src, alt, className, style, fallback, onError, onLoad }: ProxiedImageProps) {
  const [blobUrl, setBlobUrl] = useState<string | null>(null);
  const [error, setError] = useState(false);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (!src) {
      setLoading(false);
      onError?.();
      return;
    }

    const proxiedUrl = getProxiedImageUrl(src);
    if (!proxiedUrl) {
      setLoading(false);
      onError?.();
      return;
    }

    let cancelled = false;

    fetch(proxiedUrl)
      .then(res => {
        if (!res.ok) throw new Error(`HTTP ${res.status}`);
        return res.blob();
      })
      .then(blob => {
        if (!cancelled) {
          const url = URL.createObjectURL(blob);
          setBlobUrl(url);
          setLoading(false);
          onLoad?.();
        }
      })
      .catch(err => {
        console.error('Image load failed:', proxiedUrl, err);
        if (!cancelled) {
          setError(true);
          setLoading(false);
          onError?.();
        }
      });

    return () => {
      cancelled = true;
      if (blobUrl) {
        URL.revokeObjectURL(blobUrl);
      }
    };
  }, [src]);

  if (loading) {
    return (
      <div className={`${className} bg-[var(--color-surface-light)] animate-pulse`} />
    );
  }

  if (error || !blobUrl) {
    return fallback ? <>{fallback}</> : (
      <div className={`${className} bg-[var(--color-surface-light)] flex items-center justify-center`}>
        <span className="text-4xl opacity-30">👤</span>
      </div>
    );
  }

  return (
    <img
      src={blobUrl}
      alt={alt}
      className={className}
      style={style}
    />
  );
}
