
import React, { useState, useEffect } from 'react';
import { useQuery } from '@tanstack/react-query';
import { motion, AnimatePresence } from 'framer-motion';
import { RightOutlined, LeftOutlined } from '@ant-design/icons';
import { getActivities } from '../../api';
import ActivityCard from './ActivityCard';
import styles from './activity.module.less';
import { fadeInUp, staggerContainer } from '../../animation';

const ActivityList = () => {
  const { data: activities, isLoading, error } = useQuery({
    queryKey: ['activities'],
    queryFn: async () => {
      const res = await getActivities();
      // Handle different response structures
      return Array.isArray(res.data) ? res.data : (res.data?.results || []);
    },
    staleTime: 5 * 60 * 1000, // 5 minutes cache
  });

  const [currentIndex, setCurrentIndex] = useState(0);

  // Auto-play for desktop carousel
  useEffect(() => {
    if (!activities || activities.length <= 1) return;
    const interval = setInterval(() => {
      setCurrentIndex((prev) => (prev + 1) % activities.length);
    }, 5000);
    return () => clearInterval(interval);
  }, [activities]);

  const nextSlide = () => {
    if (!activities) return;
    setCurrentIndex((prev) => (prev + 1) % activities.length);
  };

  const prevSlide = () => {
    if (!activities) return;
    setCurrentIndex((prev) => (prev - 1 + activities.length) % activities.length);
  };

  if (isLoading) return <div className={styles.loading}>Loading activities...</div>;
  if (error) return null; // Or error state
  if (!activities || activities.length === 0) return null;

  return (
    <motion.div 
      className={styles.activitySection}
      initial="hidden"
      whileInView="visible"
      viewport={{ once: true, amount: 0.2 }}
      variants={staggerContainer}
    >
      <div className={styles.header}>
        <h2 className={styles.sectionTitle}>
          近期活动 / EVENTS
        </h2>
        <div className={styles.controls}>
          <button onClick={prevSlide} className={styles.navBtn}><LeftOutlined /></button>
          <button onClick={nextSlide} className={styles.navBtn}><RightOutlined /></button>
        </div>
      </div>

      {/* Desktop: Carousel (Show one prominent, but allows list structure if needed) 
          User said: "Activity only shows one, and in the form of a sliding page"
      */}
      <div className={styles.desktopCarousel}>
         <AnimatePresence mode='wait'>
            <motion.div
              key={currentIndex}
              initial={{ opacity: 0, x: 50 }}
              animate={{ opacity: 1, x: 0 }}
              exit={{ opacity: 0, x: -50 }}
              transition={{ duration: 0.5 }}
              style={{ width: '100%' }}
            >
              <ActivityCard activity={activities[currentIndex]} />
            </motion.div>
         </AnimatePresence>
         
         <div className={styles.dots}>
            {activities.map((_, idx) => (
              <span 
                key={idx} 
                className={`${styles.dot} ${idx === currentIndex ? styles.activeDot : ''}`}
                onClick={() => setCurrentIndex(idx)}
              />
            ))}
         </div>
      </div>

      {/* Mobile: Vertical List/Scroll as requested "Mobile vertical scroll" */}
      <div className={styles.mobileList}>
        {activities.map((item, index) => (
          <motion.div key={item.id} variants={fadeInUp} custom={index}>
             <ActivityCard activity={item} />
          </motion.div>
        ))}
      </div>
    </motion.div>
  );
};

export default ActivityList;
