import React, { useEffect, useState, useCallback, useRef } from 'react';
import { Link } from 'react-router-dom';
import { getLatestReviews, listMedia, listUsersRankedByReviews, getFileUrl, getFeaturedMedia } from '../services/pocketbaseService';
import { useAuth } from '../contexts/AuthContext';
import LatestReviewsMarquee from '../components/reviews/LatestReviewsMarquee';
import { FaFire, FaUsers, FaCrown, FaMedal } from 'react-icons/fa';
import StatsSection from '../components/home/StatsSection';
import GridMotion from '../components/reactbits/Backgrounds/GridMotion/GridMotion.jsx';
import { useProfileActions } from '../contexts/ProfileActionsContext';
import { getMediaCount, getReviewsCount } from '../services/pocketbaseService';
import { FaBook, FaTrophy, FaUser, FaCog } from 'react-icons/fa';
import { useClickSpark } from '../contexts/ClickSparkContext';
import HeroSection from '../components/home/HeroSection';
import GridSection from '../components/home/GridSection';
import FeaturedMedia from '../components/home/FeaturedMedia';
import TiltedCard from '../components/reactbits/Components/TiltedCard/TiltedCard';
import { motion, AnimatePresence } from 'framer-motion';
import MediaCard from '../components/media/MediaCard';
import { useMedia } from '../contexts/MediaContext';
import './HomePage.css';

const HomePage = () => {
  const { userProfile } = useAuth();
  const { profile } = useProfileActions();
  const { addSpark } = useClickSpark();
  const [popularMedia, setPopularMedia] = useState([]);
  const [latestAddedMedia, setLatestAddedMedia] = useState([]);
  const [latestReviews, setLatestReviews] = useState([]);
  const [topUsers, setTopUsers] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [stats, setStats] = useState({ mediaCount: 0, reviewsCount: 0 });
  const [posters, setPosters] = useState([]);
  const [featuredMedia, setFeaturedMedia] = useState([]);
  const [isDataReady, setIsDataReady] = useState(false);
  const popularContainerRef = useRef(null);
  const [canScrollLeft, setCanScrollLeft] = useState(false);
  const [canScrollRight, setCanScrollRight] = useState(false);

  const containerVariants = {
    hidden: { opacity: 0 },
    visible: {
      opacity: 1,
      transition: {
        staggerChildren: 0.1,
        delayChildren: 0.5
      }
    }
  };

  const itemVariants = {
    hidden: { opacity: 0, y: 20 },
    visible: {
      opacity: 1,
      y: 0,
      transition: {
        duration: 0.5,
        ease: "easeOut"
      }
    }
  };

  const loadingVariants = {
    initial: { opacity: 0 },
    animate: { 
      opacity: 1,
      transition: {
        duration: 0.5
      }
    },
    exit: { 
      opacity: 0,
      transition: {
        duration: 0.5
      }
    }
  };

  const checkScroll = useCallback(() => {
    if (!popularContainerRef.current) return;
    
    const container = popularContainerRef.current;
    const { scrollLeft, scrollWidth, clientWidth } = container;
    
    // Добавляем отладочную информацию
    console.log('Scroll check:', {
      scrollLeft,
      scrollWidth,
      clientWidth,
      canScrollLeft: scrollLeft > 0,
      canScrollRight: scrollLeft < scrollWidth - clientWidth - 1
    });
    
    setCanScrollLeft(scrollLeft > 0);
    setCanScrollRight(scrollLeft < scrollWidth - clientWidth - 1);
  }, []);

  useEffect(() => {
    const container = popularContainerRef.current;
    if (!container) return;

    // Принудительно проверяем состояние после монтирования
    setTimeout(() => {
      checkScroll();
    }, 100);

    container.addEventListener('scroll', checkScroll);
    window.addEventListener('resize', checkScroll);

    return () => {
      container.removeEventListener('scroll', checkScroll);
      window.removeEventListener('resize', checkScroll);
    };
  }, [checkScroll, popularMedia]);

  const scroll = (direction) => {
    if (!popularContainerRef.current) return;

    const container = popularContainerRef.current;
    const scrollAmount = container.clientWidth * 0.8;

    // Если достигли конца вправо, переходим в начало
    if (direction === 'right' && container.scrollLeft >= container.scrollWidth - container.clientWidth - 10) {
      container.scrollTo({
        left: 0,
        behavior: 'smooth'
      });
      return;
    }

    // Если достигли начала влево, переходим в конец
    if (direction === 'left' && container.scrollLeft <= 10) {
      container.scrollTo({
        left: container.scrollWidth,
        behavior: 'smooth'
      });
      return;
    }

    container.scrollBy({
      left: direction === 'left' ? -scrollAmount : scrollAmount,
      behavior: 'smooth'
    });
  };

  // Добавляем эффект для принудительной проверки при изменении данных
  useEffect(() => {
    if (popularMedia.length > 0) {
      // Даем время на рендеринг и загрузку изображений
      setTimeout(checkScroll, 500);
    }
  }, [popularMedia, checkScroll]);

  const fetchData = useCallback(async () => {
    try {
      setLoading(true);
      setError(null);

      const [
        popularMediaData,
        latestAddedMediaData,
        latestReviewsData,
        topUsersData,
        mediaCount,
        reviewsCount
      ] = await Promise.all([
        listMedia(null, 1, 50, userProfile, true, true, '-review_count'),
        listMedia(null, 1, 30, userProfile, false, true, '-created'),
        getLatestReviews(10),
        listUsersRankedByReviews(3),
        getMediaCount(),
        getReviewsCount()
      ]);
      
      if (popularMediaData?.data) setPopularMedia(popularMediaData.data);
      if (latestAddedMediaData?.data) setLatestAddedMedia(latestAddedMediaData.data);
      if (latestReviewsData) setLatestReviews(latestReviewsData);
      if (topUsersData) setTopUsers(topUsersData);

      setStats({
        mediaCount: parseInt(mediaCount) || 0,
        reviewsCount: parseInt(reviewsCount) || 0
      });

      if (latestAddedMediaData?.data) {
        const posterUrls = latestAddedMediaData.data
          .filter(item => item.poster)
          .slice(0, 30)
          .map(item => getFileUrl(item, 'poster'));

        setPosters(posterUrls);
      }

      await new Promise(resolve => setTimeout(resolve, 1000));
      setIsDataReady(true);
      setLoading(false);

    } catch (err) {
      console.error('[HomePage] Ошибка загрузки данных:', err);
      setError('Не удалось загрузить данные главной страницы.');
      setLoading(false);
    }
  }, [userProfile]);

  useEffect(() => {
    fetchData();
  }, [fetchData]);

  useEffect(() => {
    const fetchFeaturedMedia = async () => {
      try {
        const media = await getFeaturedMedia();
        if (media) setFeaturedMedia(media);
      } catch (error) {
        console.error('Error fetching featured media:', error);
      }
    };

    fetchFeaturedMedia();
  }, []);

  if (error) {
    return (
      <div className="min-h-screen bg-campfire-dark pt-20 flex justify-center items-center">
        <div className="bg-status-error/20 text-status-error p-4 rounded-lg text-center">
          {error}
        </div>
      </div>
    );
  }

  // Helper function to get pedestal styles based on rank
  const getPedestalStyles = (rank) => {
      switch (rank) {
          case 1:
              return {
                  container: 'bg-gradient-to-br from-yellow-400 to-yellow-600 text-campfire-dark border-yellow-700',
                  avatarBorder: 'border-yellow-700',
                  iconColor: 'text-yellow-800',
                  crown: <FaCrown className="text-yellow-800 text-3xl absolute -top-4 right-1/2 translate-x-1/2" />
              };
          case 2:
              return {
                  container: 'bg-gradient-to-br from-gray-400 to-gray-600 text-campfire-dark border-gray-700',
                  avatarBorder: 'border-gray-700',
                  iconColor: 'text-gray-800',
                  medal: <FaMedal className="text-gray-800 text-2xl absolute -top-3 right-1/2 translate-x-1/2" />
              };
          case 3:
              return {
                  container: 'bg-gradient-to-br from-amber-700 to-amber-900 text-campfire-dark border-amber-950',
                  avatarBorder: 'border-amber-950',
                  iconColor: 'text-amber-950',
                  medal: <FaMedal className="text-amber-950 text-2xl absolute -top-3 right-1/2 translate-x-1/2" />
              };
          default:
              return {
                  container: 'bg-campfire-charcoal text-campfire-light border-campfire-ash/20',
                  avatarBorder: 'border-campfire-dark',
                  iconColor: 'text-campfire-amber'
              };
      }
  };

  const renderTopReviewers = () => {
    return (
        <div className="space-y-4">
            {topUsers.map((user) => (
                <div key={user.id} className="flex items-center space-x-4 bg-campfire-dark/50 p-4 rounded-lg">
                    <Link to={`/profile/${user.login}`} className="flex-shrink-0">
                        <img
                            src={getFileUrl(user, 'profile_picture', { thumb: '100x100' }) || '/default-avatar.png'}
                            alt={user.username}
                            className="w-12 h-12 rounded-full object-cover"
                        />
                    </Link>
                    <div className="flex-grow">
                        <Link to={`/profile/${user.login}`} className="text-campfire-light hover:text-campfire-gold">
                            <h3 className="text-lg font-semibold">{user.username}</h3>
                        </Link>
                        <p className="text-campfire-ash text-sm">Рецензий: {user.review_count}</p>
                    </div>
                </div>
            ))}
        </div>
    );
  };

  const PopularSection = ({ popularMedia }) => {
    const containerRef = useRef(null);
    const [canScrollLeft, setCanScrollLeft] = useState(false);
    const [canScrollRight, setCanScrollRight] = useState(false);

    const checkScroll = useCallback(() => {
      if (!containerRef.current) return;
      
      const { scrollLeft, scrollWidth, clientWidth } = containerRef.current;
      setCanScrollLeft(scrollLeft > 0);
      setCanScrollRight(scrollLeft < scrollWidth - clientWidth - 1);
    }, []);

    useEffect(() => {
      const container = containerRef.current;
      if (!container) return;

      checkScroll();
      container.addEventListener('scroll', checkScroll);
      window.addEventListener('resize', checkScroll);

      return () => {
        container.removeEventListener('scroll', checkScroll);
        window.removeEventListener('resize', checkScroll);
      };
    }, [checkScroll, popularMedia]);

    const scroll = (direction) => {
      if (!containerRef.current) return;

      const container = containerRef.current;
      const scrollAmount = container.clientWidth * 0.8; // Прокручиваем на 80% ширины контейнера

      container.scrollBy({
        left: direction === 'left' ? -scrollAmount : scrollAmount,
        behavior: 'smooth'
      });
    };

    return (
      <section className="py-8">
        <div className="flex justify-between items-center mb-6">
          <div className="flex items-center space-x-4">
            <div className="w-1 h-8 bg-campfire-amber/20 rounded-full"></div>
            <h2 className="text-2xl font-bold text-campfire-light">Популярное</h2>
          </div>
          <div className="flex items-center space-x-2">
            <button 
              onClick={() => scroll('left')}
              className="w-8 h-8 rounded-full bg-campfire-charcoal/20 border border-campfire-ash/10 flex items-center justify-center text-campfire-light transition-all duration-300 hover:bg-campfire-amber/10 hover:border-campfire-amber/20"
            >
              <svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
              </svg>
            </button>
            <button 
              onClick={() => scroll('right')}
              className="w-8 h-8 rounded-full bg-campfire-charcoal/20 border border-campfire-ash/10 flex items-center justify-center text-campfire-light transition-all duration-300 hover:bg-campfire-amber/10 hover:border-campfire-amber/20"
            >
              <svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
              </svg>
            </button>
          </div>
        </div>

        <div className="relative group">
          {/* Градиентные затемнения по бокам */}
          <div className="absolute left-0 top-0 bottom-0 w-16 bg-gradient-to-r from-campfire-dark to-transparent z-10 pointer-events-none"></div>
          <div className="absolute right-0 top-0 bottom-0 w-16 bg-gradient-to-l from-campfire-dark to-transparent z-10 pointer-events-none"></div>

          <div 
            ref={containerRef}
            className="flex overflow-x-auto pb-4 gap-4 scrollbar-none"
            style={{ scrollbarWidth: 'none', msOverflowStyle: 'none' }}
          >
            {popularMedia.map(media => (
              <div key={media.id} className="flex-none w-64 transform transition-transform duration-300 hover:scale-105">
                <MediaCard media={media} />
              </div>
            ))}
          </div>
        </div>
      </section>
    );
  };

  // Добавляем стили для скрытия скроллбара
  const styles = `
    .hide-scrollbar {
      -ms-overflow-style: none;
      scrollbar-width: none;
    }
    .hide-scrollbar::-webkit-scrollbar {
      display: none;
    }
  `;

  return (
    <AnimatePresence mode="wait">
      {loading || !isDataReady ? (
        <motion.div
          key="loading"
          className="min-h-screen bg-campfire-dark pt-20 flex justify-center items-center"
          variants={loadingVariants}
          initial="initial"
          animate="animate"
          exit="exit"
        >
          <div className="flex flex-col items-center gap-4">
            <div className="animate-spin rounded-full h-16 w-16 border-t-2 border-b-2 border-campfire-amber"></div>
            <motion.p 
              className="text-campfire-light text-lg"
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              transition={{ delay: 0.5 }}
            >
              Загрузка...
            </motion.p>
          </div>
        </motion.div>
      ) : (
        <motion.div 
          key="content"
          className="min-h-screen bg-campfire-dark"
          initial="hidden"
          animate="visible"
          variants={containerVariants}
        >
          <div>
            {/* Grid Section with Stats Overlay */}
            <motion.div variants={itemVariants}>
              <GridSection posters={posters} stats={stats} />
            </motion.div>

            {/* Marquee for Latest Reviews */}
            <motion.div variants={itemVariants}>
              <LatestReviewsMarquee reviews={latestReviews} />
            </motion.div>

            {/* Content Grid */}
            <motion.div 
              className="py-8 grid grid-cols-1 gap-8 mx-auto max-w-screen-xl px-4 sm:px-6 lg:px-8"
              variants={containerVariants}
            >
              <div className="space-y-12">
                {/* Popular Section */}
                <motion.div variants={itemVariants}>
                  <div className="flex justify-between items-center mb-6">
                    <div className="flex items-center space-x-4">
                      <div className="w-1 h-8 bg-campfire-amber/20 rounded-full"></div>
                      <h2 className="text-2xl font-bold text-campfire-light">Популярное</h2>
                    </div>
                    <div className="flex items-center space-x-2">
                      <button 
                        onClick={() => scroll('left')}
                        className="w-8 h-8 rounded-full bg-campfire-charcoal/20 border border-campfire-ash/10 flex items-center justify-center text-campfire-light transition-all duration-300 hover:bg-campfire-amber/10 hover:border-campfire-amber/20"
                      >
                        <svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
                        </svg>
                      </button>
                      <button 
                        onClick={() => scroll('right')}
                        className="w-8 h-8 rounded-full bg-campfire-charcoal/20 border border-campfire-ash/10 flex items-center justify-center text-campfire-light transition-all duration-300 hover:bg-campfire-amber/10 hover:border-campfire-amber/20"
                      >
                        <svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
                        </svg>
                      </button>
                    </div>
                  </div>
                  {popularMedia.length > 0 ? (
                    <div className="relative">
                      {/* Градиенты по бокам */}
                      <div className="absolute left-0 top-0 bottom-0 w-24 bg-gradient-to-r from-campfire-dark to-transparent z-10 pointer-events-none"></div>
                      <div className="absolute right-0 top-0 bottom-0 w-24 bg-gradient-to-l from-campfire-dark to-transparent z-10 pointer-events-none"></div>
                      
                      <div 
                        ref={popularContainerRef}
                        className="overflow-x-auto pb-8 custom-scrollbar scroll-smooth px-6"
                        style={{ 
                          scrollbarWidth: 'none', 
                          msOverflowStyle: 'none'
                        }}
                      >
                        <div className="flex space-x-8 min-w-max">
                          {/* Дублируем карточки для бесконечной прокрутки */}
                          {[...popularMedia].map((mediaItem, index) => (
                            <motion.div
                              key={`${mediaItem.id}-${index}`}
                              variants={itemVariants}
                              whileHover={{ scale: 1.05 }}
                              transition={{ duration: 0.2 }}
                              className="flex-none w-80 transform-gpu"
                            >
                              <MediaCard
                                media={mediaItem}
                                userProfile={userProfile}
                                isSmallCard={true}
                              />
                            </motion.div>
                          ))}
                        </div>
                      </div>
                    </div>
                  ) : (
                    <p className="text-campfire-ash text-center py-8">Нет данных о популярном медиа.</p>
                  )}
                </motion.div>

                {/* Top Users Section */}
                <motion.div variants={itemVariants}>
                  <h2 className="text-2xl font-bold text-campfire-light mb-6 border-b border-campfire-ash/20 pb-4">Топ рецензенты</h2>
                  {topUsers.length > 0 ? (
                    <div className="flex flex-col items-center space-y-6">
                      {/* Pedestal Layout */}
                      <div className="flex justify-center items-end w-full gap-4">
                        {/* Second Place */}
                        {topUsers[1] && (
                          <motion.div 
                            className="flex flex-col items-center w-1/3"
                            variants={itemVariants}
                          >
                            <div className="relative">
                              <div className="w-24 h-24 rounded-full overflow-hidden border-2 border-campfire-ash/30 mb-2">
                                <img
                                  src={topUsers[1].profile_picture ? getFileUrl(topUsers[1], 'profile_picture') : 'https://via.placeholder.com/150'}
                                  alt={topUsers[1].username}
                                  className="w-full h-full object-cover"
                                />
                              </div>
                              <div className="absolute -top-2 -right-2 w-8 h-8 bg-campfire-ash/30 rounded-full flex items-center justify-center">
                                <span className="text-campfire-light font-bold">2</span>
                              </div>
                            </div>
                            <Link to={`/profile/${topUsers[1].login}`} className="text-campfire-light hover:text-campfire-amber font-medium">
                              {topUsers[1].username}
                            </Link>
                            <span className="text-campfire-ash text-sm">{topUsers[1].review_count} рецензий</span>
                          </motion.div>
                        )}

                        {/* First Place */}
                        {topUsers[0] && (
                          <motion.div 
                            className="flex flex-col items-center w-1/3"
                            variants={itemVariants}
                          >
                            <div className="relative">
                              <div className="w-32 h-32 rounded-full overflow-hidden border-2 border-campfire-amber mb-2">
                                <img
                                  src={topUsers[0].profile_picture ? getFileUrl(topUsers[0], 'profile_picture') : 'https://via.placeholder.com/150'}
                                  alt={topUsers[0].username}
                                  className="w-full h-full object-cover"
                                />
                              </div>
                              <div className="absolute -top-2 -right-2 w-8 h-8 bg-campfire-amber rounded-full flex items-center justify-center">
                                <span className="text-campfire-dark font-bold">1</span>
                              </div>
                            </div>
                            <Link to={`/profile/${topUsers[0].login}`} className="text-campfire-light hover:text-campfire-amber font-medium">
                              {topUsers[0].username}
                            </Link>
                            <span className="text-campfire-ash text-sm">{topUsers[0].review_count} рецензий</span>
                          </motion.div>
                        )}

                        {/* Third Place */}
                        {topUsers[2] && (
                          <motion.div 
                            className="flex flex-col items-center w-1/3"
                            variants={itemVariants}
                          >
                            <div className="relative">
                              <div className="w-24 h-24 rounded-full overflow-hidden border-2 border-campfire-ember/30 mb-2">
                                <img
                                  src={topUsers[2].profile_picture ? getFileUrl(topUsers[2], 'profile_picture') : 'https://via.placeholder.com/150'}
                                  alt={topUsers[2].username}
                                  className="w-full h-full object-cover"
                                />
                              </div>
                              <div className="absolute -top-2 -right-2 w-8 h-8 bg-campfire-ember/30 rounded-full flex items-center justify-center">
                                <span className="text-campfire-light font-bold">3</span>
                              </div>
                            </div>
                            <Link to={`/profile/${topUsers[2].login}`} className="text-campfire-light hover:text-campfire-amber font-medium">
                              {topUsers[2].username}
                            </Link>
                            <span className="text-campfire-ash text-sm">{topUsers[2].review_count} рецензий</span>
                          </motion.div>
                        )}
                      </div>
                      <Link to="/rating" className="text-campfire-amber hover:underline mt-4">
                        Посмотреть полный рейтинг
                      </Link>
                    </div>
                  ) : (
                    <p className="text-campfire-ash text-center py-8">Нет данных о топ рецензентах.</p>
                  )}
                </motion.div>

                {/* Latest Added Section */}
                <motion.div variants={itemVariants}>
                  <h2 className="text-2xl font-bold text-campfire-light mb-6 border-b border-campfire-ash/20 pb-4">Последнее добавленное</h2>
                  {latestAddedMedia.length > 0 ? (
                    <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-5 gap-8 md:gap-20">
                      {latestAddedMedia.map((mediaItem) => (
                        <motion.div
                          key={mediaItem.id}
                          variants={itemVariants}
                          whileHover={{ scale: 1.05 }}
                          transition={{ duration: 0.2 }}
                        >
                          <Link 
                            to={`/media/${mediaItem.path}`}
                            className="block group"
                          >
                            <TiltedCard
                              imageSrc={mediaItem.poster ? getFileUrl(mediaItem, 'poster', { thumb: '300x450' }) : 'https://via.placeholder.com/300x450'}
                              altText={mediaItem.title}
                              captionText={mediaItem.title}
                              containerHeight="360px"
                              containerWidth="100%"
                              imageHeight="360px"
                              imageWidth="240px"
                              scaleOnHover={1.05}
                              rotateAmplitude={10}
                              showMobileWarning={false}
                              showTooltip={true}
                              displayOverlayContent={false}
                              rating={mediaItem.average_rating}
                              releaseDate={mediaItem.release_date}
                            />
                          </Link>
                        </motion.div>
                      ))}
                    </div>
                  ) : (
                    <p className="text-campfire-ash text-center py-8">Нет данных о последнем добавленном медиа.</p>
                  )}
                </motion.div>
              </div>
            </motion.div>
          </div>
          <motion.div variants={itemVariants}>
            <FeaturedMedia media={featuredMedia} />
          </motion.div>
        </motion.div>
      )}
    </AnimatePresence>
  );
};

export default HomePage;