import React, { useState, useEffect } from "react";
import { ImageIcon, InfoCircledIcon } from "@radix-ui/react-icons";

const CourseCoverImage = ({ coverImageUrl }) => {
  const [isLoading, setIsLoading] = useState(true);
  const [isError, setIsError] = useState(false);
  const [loadedSrc, setLoadedSrc] = useState(null);

  useEffect(() => {
    const imageLoader = new Image();
    imageLoader.src = coverImageUrl;
    imageLoader.onload = () => {
      setIsLoading(false);
      setLoadedSrc(coverImageUrl);
    };
    imageLoader.onerror = () => {
      setIsError(true);
      setIsLoading(false);
    };
  }, [coverImageUrl]);
  return (
    <div>
      {!isError && (
        <div className="animate-pulse absolute inset-0 flex items-center justify-center bg-gray-100">
          <ImageIcon className="w-[50%] h-[50%] text-gray-400" />
        </div>
      )}

      {!isLoading && !isError && (
        <img
          src={loadedSrc}
          alt={coverImageUrl}
          className="absolute inset-0 w-full h-full object-cover mb-4 group-hover:scale-110 transition-transform duration-300"
        />
      )}
      {!isLoading && isError && (
        <img
          src={process.env.PUBLIC_URL + "/course.jpeg"}
          alt={coverImageUrl}
          className="absolute inset-0 w-full h-full object-cover mb-4 group-hover:scale-110 transition-transform duration-300"
        />
        // <div className="absolute inset-0 flex items-center justify-center bg-gray-100">
        //   <span className="text-gray-400">图像加载失败</span>
        //   <InfoCircledIcon className="text-gray-400 w-4 h-4 ml-1"></InfoCircledIcon>
        // </div>
      )}
    </div>
  );
};

export default CourseCoverImage;
