
import React, { useState, useRef, useLayoutEffect } from 'react';
import { motion } from 'framer-motion';
import { CalendarOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import styles from './activity.module.less';
import { hoverScale } from '../../animation';

const ActivityCard = ({ activity }) => {
  const navigate = useNavigate();
  const [isLoaded, setIsLoaded] = useState(false);
  const [hasError, setHasError] = useState(false);
  const imgRef = useRef(null);

  const handleCardClick = () => {
    navigate(`/activity/${activity.id}`);
  };

  const getStatus = (startTime) => {
    const now = new Date();
    const start = new Date(startTime);
    if (now < start) return '即将开始';
    return '报名中';
  };

  const formatDate = (dateStr) => {
    if (!dateStr) return 'TBD';
    const date = new Date(dateStr);
    return date.toLocaleDateString('zh-CN', { month: 'long', day: 'numeric' });
  };

  const imgSrc = hasError 
    ? 'https://via.placeholder.com/600x400?text=No+Image' 
    : (activity.display_banner_url || activity.banner_url || activity.cover_image || 'https://via.placeholder.com/600x400');

  // Check if image is already loaded (cached) to prevent flashing
  useLayoutEffect(() => {
    if (imgRef.current && imgRef.current.complete) {
      setIsLoaded(true);
    }
  }, [imgSrc]);

  return (
    <motion.div
      className={styles.activityCard}
      variants={hoverScale}
      whileHover="hover"
      onClick={handleCardClick}
      layoutId={`activity-card-${activity.id}`}
      style={{ willChange: 'transform' }}
    >
      <div className={styles.imageContainer}>
        {/* Placeholder Background - Always visible behind the image */}
        <div 
          style={{
            position: 'absolute',
            top: 0,
            left: 0,
            width: '100%',
            height: '100%',
            backgroundColor: '#f5f5f5',
            zIndex: 0,
          }}
        />
        
        <img
          ref={imgRef}
          src={imgSrc}
          alt={activity.title}
          style={{ 
            position: 'relative', 
            zIndex: 1,
            width: '100%',
            height: '100%',
            objectFit: 'cover',
            opacity: isLoaded ? 1 : 0,
            transition: 'opacity 0.3s ease-out'
          }}
          onLoad={() => setIsLoaded(true)}
          onError={() => {
            setHasError(true);
            setIsLoaded(true);
          }}
          loading="lazy"
        />
        <div className={styles.overlay} style={{ zIndex: 2 }}>
          <div className={styles.statusTag}>
            {activity.status || getStatus(activity.start_time)}
          </div>
          <h3 className={styles.title}>{activity.title}</h3>
          <div className={styles.time}>
            <CalendarOutlined />
            <span>{formatDate(activity.start_time)}</span>
          </div>
        </div>
      </div>
    </motion.div>
  );
};

export default ActivityCard;
