import React, { useEffect, useState } from 'react';
import { Avatar, AvatarFallback } from '@/components/ui/avatar';
import { Skeleton } from '@/components/ui/skeleton';
import { getResourceImage } from '@/plugins/imagePlugin';

interface ResourceImageProps {
  resourceName: string;
  className?: string;
  alt?: string;
  fallback?: string;
}

const ResourceImage: React.FC<ResourceImageProps> = ({
  resourceName,
  className = "h-12 w-12",
  alt = "이미지",
  fallback = "ZY"
}) => {
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(false);
  const [imageSrc, setImageSrc] = useState<string>("");

  useEffect(() => {
    const loadResourceImage = async () => {
      try {
        const imgSrc = await getResourceImage(resourceName);
        setImageSrc(imgSrc);
        setLoading(false);
      } catch (err) {
        console.error('이미지 로드 실패:', err);
        setError(true);
        setLoading(false);
      }
    };

    loadResourceImage();
  }, [resourceName]);

  return (
    <Avatar className={className}>
      {loading ? (
        <div className="h-full w-full flex items-center justify-center">
          <Skeleton className="h-full w-full rounded-full" />
        </div>
      ) : error ? (
        <AvatarFallback delayMs={0}>{fallback}</AvatarFallback>
      ) : (
        <img
          src={imageSrc}
          alt={alt}
          className="h-full w-full object-cover"
          onError={() => setError(true)}
        />
      )}
    </Avatar>
  );
};

export default ResourceImage;
