import React, { useEffect, useState, useCallback } from 'react';
import { Link } from 'react-router-dom';
import { listMedia, listUsersRankedByReviews, listUsersRankedByLevel, mediaTypes, getFileUrl, getReviewsByLikes } from '../services/pocketbaseService';
import { useAuth } from '../contexts/AuthContext';
import { useProfileActions } from '../contexts/ProfileActionsContext';
import TiltedCard from '../components/reactbits/Components/TiltedCard/TiltedCard';
import { FaFire, FaStar, FaUsers, FaLevelUpAlt, FaMedal, FaHeart } from 'react-icons/fa';

const RatingPage = () => {
    const { userProfile } = useAuth();
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);
    const [activeTab, setActiveTab] = useState('media');

    const [mediaByRating, setMediaByRating] = useState([]);
    const [mediaByReviews, setMediaByReviews] = useState([]);
    const [usersByReviews, setUsersByReviews] = useState([]);
    const [usersByLevel, setUsersByLevel] = useState([]);
    const [reviewsByLikes, setReviewsByLikes] = useState([]);

    useEffect(() => {
        window.scrollTo(0, 0);
    }, []);

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

            const [
                mediaRatingData,
                mediaReviewsData,
                usersReviewsData,
                usersLevelData,
                reviewsLikesData
            ] = await Promise.all([
                listMedia(null, 1, 20, userProfile, false, true, '-average_rating'),
                listMedia(null, 1, 20, userProfile, false, true, '-review_count'),
                listUsersRankedByReviews(20),
                listUsersRankedByLevel(20),
                getReviewsByLikes(20)
            ]);

            setMediaByRating(mediaRatingData.data || []);
            setMediaByReviews(mediaReviewsData.data || []);
            setUsersByReviews(usersReviewsData || []);
            setUsersByLevel(usersLevelData || []);
            setReviewsByLikes(reviewsLikesData || []);

        } catch (err) {
            console.error('Error fetching rating data:', err);
            setError('Не удалось загрузить данные рейтинга.');
        } finally {
            setLoading(false);
        }
    }, [userProfile]);

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

    const renderMediaList = (mediaItems) => (
        <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-5 gap-8 md:gap-20">
            {mediaItems.map((mediaItem) => (
                <Link to={`/media/${mediaItem.path}`} key={mediaItem.id} className="block">
                    <TiltedCard 
                        imageSrc={getFileUrl(mediaItem, 'poster')} 
                        altText={mediaItem.title}
                        captionText={mediaItem.title}
                        containerHeight="360px"
                        containerWidth="100%"
                        imageHeight="360px"
                        imageWidth="240px"
                        scaleOnHover={1.05}
                        rotateAmplitude={10}
                        showMobileWarning={false}
                        showTooltip={false}
                        displayOverlayContent={false}
                        rating={mediaItem.average_rating}
                        releaseDate={mediaItem.release_date}
                    />
                </Link>
            ))}
        </div>
    );

    const renderUserList = (userItems, rankType) => (
        <div className="space-y-4">
            {userItems.map((user, index) => (
                <Link to={`/profile/${user.login}`} key={user.id} className="bg-campfire-charcoal rounded-lg shadow-md p-4 flex items-center border border-campfire-ash/20 hover:border-campfire-amber transition-colors duration-200">
                    <span className="text-campfire-amber font-bold text-xl mr-4 w-8 text-center">{index + 1}.</span>
                    <img
                        src={getFileUrl(user, 'profile_picture') || 'https://images.pexels.com/photos/1704488/pexels-photo-1704488.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1'}
                        alt={user.username}
                        className="w-12 h-12 rounded-full object-cover mr-4 border border-campfire-ash/30"
                    />
                    <div className="flex-grow">
                        <h3 className="text-lg font-semibold text-campfire-light">{user.username}</h3>
                        {rankType === 'reviews' && (
                            <p className="text-campfire-ash text-sm">Рецензий: <b className="text-campfire-amber">{user.review_count || 0}</b></p>
                        )}
                        {rankType === 'level' && (
                            <p className="text-campfire-ash text-sm">Уровень: <b className="text-campfire-amber">{user.level || 1}</b></p>
                        )}
                    </div>
                </Link>
            ))}
        </div>
    );

    const renderReviewList = (reviews) => (
        <div className="space-y-4">
            {reviews.map((review, index) => (
                <Link to={`/media/${review.expand.media_id.path}`} key={review.id} className="block">
                    <div className="bg-campfire-charcoal rounded-lg shadow-md p-4 border border-campfire-ash/20 hover:border-campfire-amber transition-colors duration-200">
                        <div className="flex items-center mb-2">
                            <span className="text-campfire-amber font-bold text-xl mr-4 w-8 text-center">{index + 1}.</span>
                            <div className="flex-grow">
                                <h3 className="text-lg font-semibold text-campfire-light">{review.expand.media_id.title}</h3>
                                <p className="text-campfire-ash text-sm">Автор: {review.expand.user_id.username}</p>
                            </div>
                            <div className="flex items-center text-campfire-amber">
                                <FaHeart className="mr-1" />
                                <span>{review.likes?.length || 0}</span>
                            </div>
                        </div>
                        <div className="text-campfire-ash line-clamp-2" dangerouslySetInnerHTML={{ __html: review.content }} />
                    </div>
                </Link>
            ))}
        </div>
    );

    if (loading) {
        return (
            <div className="min-h-screen bg-campfire-dark pt-20 flex justify-center items-center">
                <div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-campfire-amber"></div>
            </div>
        );
    }

    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>
        );
    }

    return (
        <div className="min-h-screen bg-campfire-dark pt-20 container-custom py-8">
            <h1 className="text-3xl font-bold mb-6 text-campfire-light">Рейтинги</h1>

            <div className="flex border-b border-campfire-ash/20 mb-8 overflow-x-auto">
                <button
                    className={`px-4 py-2 text-sm font-medium ${activeTab === 'media-rating' ? 'text-campfire-amber border-b-2 border-campfire-amber' : 'text-campfire-ash hover:text-campfire-light'}`}
                    onClick={() => setActiveTab('media-rating')}
                >
                    Медиа по рейтингу
                </button>
                <button
                    className={`px-4 py-2 text-sm font-medium ${activeTab === 'media-reviews' ? 'text-campfire-amber border-b-2 border-campfire-amber' : 'text-campfire-ash hover:text-campfire-light'}`}
                    onClick={() => setActiveTab('media-reviews')}
                >
                    Медиа по рецензиям
                </button>
                <button
                    className={`px-4 py-2 text-sm font-medium ${activeTab === 'reviews-likes' ? 'text-campfire-amber border-b-2 border-campfire-amber' : 'text-campfire-ash hover:text-campfire-light'}`}
                    onClick={() => setActiveTab('reviews-likes')}
                >
                    Рецензии по лайкам
                </button>
                <button
                    className={`px-4 py-2 text-sm font-medium ${activeTab === 'users-reviews' ? 'text-campfire-amber border-b-2 border-campfire-amber' : 'text-campfire-ash hover:text-campfire-light'}`}
                    onClick={() => setActiveTab('users-reviews')}
                >
                    Пользователи по рецензиям
                </button>
                <button
                    className={`px-4 py-2 text-sm font-medium ${activeTab === 'users-level' ? 'text-campfire-amber border-b-2 border-campfire-amber' : 'text-campfire-ash hover:text-campfire-light'}`}
                    onClick={() => setActiveTab('users-level')}
                >
                    Пользователи по уровню
                </button>
            </div>

            <div>
                {activeTab === 'media-rating' && (
                    mediaByRating.length > 0 ? renderMediaList(mediaByRating) : <p className="text-campfire-ash text-center py-8">Нет данных для этого рейтинга.</p>
                )}
                {activeTab === 'media-reviews' && (
                    mediaByReviews.length > 0 ? renderMediaList(mediaByReviews) : <p className="text-campfire-ash text-center py-8">Нет данных для этого рейтинга.</p>
                )}
                {activeTab === 'reviews-likes' && (
                    reviewsByLikes.length > 0 ? renderReviewList(reviewsByLikes) : <p className="text-campfire-ash text-center py-8">Нет данных для этого рейтинга.</p>
                )}
                {activeTab === 'users-reviews' && (
                    usersByReviews.length > 0 ? renderUserList(usersByReviews, 'reviews') : <p className="text-campfire-ash text-center py-8">Нет данных для этого рейтинга.</p>
                )}
                {activeTab === 'users-level' && (
                    usersByLevel.length > 0 ? renderUserList(usersByLevel, 'level') : <p className="text-campfire-ash text-center py-8">Нет данных для этого рейтинга.</p>
                )}
            </div>
        </div>
    );
};

export default RatingPage;