import { useState, useEffect } from 'react';
import { ImageIcon } from '@radix-ui/react-icons';
import PropTypes from 'prop-types';

import defaultImageUrl from '../../assets/course.jpeg';

const CourseCoverImage = ({ coverImageUrl }) => {
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(false);
  const [imageSrc, setImageSrc] = useState(null);

  useEffect(() => {
    const imageLoader = new Image();
    if (coverImageUrl) {
      imageLoader.src = coverImageUrl;
    } else {
      imageLoader.src = defaultImageUrl;
    }
    imageLoader.onload = () => {
      setLoading(false);
      setImageSrc(imageLoader.src);
    };
    imageLoader.onerror = () => {
      setError(true);
      setLoading(false);
    };
  }, [coverImageUrl]);
  return (
    <div>
      {!error && (
        <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>
      )}
      {!loading && !error && (
        <img
          src={imageSrc}
          alt={coverImageUrl}
          className='absolute inset-0 w-full h-full object-cover mb-4 group-hover:scale-110 transition-transform duration-300'
        />
      )}
      {!loading && error && (
        <img
          src={defaultImageUrl}
          alt={coverImageUrl}
          className='absolute inset-0 w-full h-full object-cover mb-4 group-hover:scale-110 transition-transform duration-300'
        />
      )}
    </div>
  );
};

/// 类型校验
CourseCoverImage.propTypes = {
  coverImageUrl: PropTypes.string.isRequired,
};

export default CourseCoverImage;
