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

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

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

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

  const renderMediaList = (mediaItems) => (
    <div className="grid grid-cols-2 gap-x-4 gap-y-6 mb-8 px-4">
      {mediaItems.map((mediaItem) => (
        <Link to={`/media/${mediaItem.path}`} key={mediaItem.id} className="block">
          <div className="bg-campfire-charcoal/20 backdrop-blur-md border border-campfire-ash/30 rounded-2xl overflow-hidden">
            <img
              src={getFileUrl(mediaItem, 'poster')}
              alt={mediaItem.title}
              className="w-full aspect-[2/3] object-cover"
            />
            <div className="p-3">
              <h3 className="text-campfire-light font-semibold text-sm mb-1 line-clamp-1">
                {mediaItem.title}
              </h3>
              <div className="flex items-center space-x-2 text-xs">
                <div className="flex items-center text-campfire-amber">
                  <FaStar className="mr-1" />
                  <span>{mediaItem.average_rating?.toFixed(1) || '0.0'}</span>
                </div>
                <span className="text-campfire-ash">
                  {mediaItem.review_count || 0} обзоров
                </span>
              </div>
            </div>
          </div>
        </Link>
      ))}
    </div>
  );

  const renderUserList = (userItems, rankType) => (
    <div className="space-y-4 px-4">
      {userItems.map((user, index) => (
        <Link to={`/profile/${user.login}`} key={user.id} className="block">
          <div className="bg-campfire-charcoal/20 backdrop-blur-md border border-campfire-ash/30 rounded-2xl shadow-md p-4 flex items-center mb-4">
            <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://via.placeholder.com/150'}
              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-campfire-light font-semibold">{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>
          </div>
        </Link>
      ))}
    </div>
  );

  const renderReviewList = (reviews) => (
    <div className="space-y-4 px-4">
      {reviews.map((review, index) => (
        <Link to={`/media/${review.expand.media_id.path}`} key={review.id} className="block">
          <div className="bg-campfire-charcoal/20 backdrop-blur-md border border-campfire-ash/30 rounded-2xl p-4">
            <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-campfire-light font-semibold">{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 text-sm line-clamp-2" dangerouslySetInnerHTML={{ __html: review.content }} />
          </div>
        </Link>
      ))}
    </div>
  );

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

  if (error) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <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 pb-4">
      <h1 className="text-2xl font-bold mb-8 text-campfire-light text-center">Рейтинги</h1>

      <div className="flex overflow-x-auto space-x-2 pb-4 mb-6 px-4">
        <button
          onClick={() => setActiveTab('media-rating')}
          className={`px-4 py-2 text-sm font-medium whitespace-nowrap rounded-full ${
            activeTab === 'media-rating' 
              ? 'bg-campfire-amber text-campfire-dark' 
              : 'bg-campfire-charcoal/20 text-campfire-ash'
          }`}
        >
          Медиа по рейтингу
        </button>
        <button
          onClick={() => setActiveTab('media-reviews')}
          className={`px-4 py-2 text-sm font-medium whitespace-nowrap rounded-full ${
            activeTab === 'media-reviews' 
              ? 'bg-campfire-amber text-campfire-dark' 
              : 'bg-campfire-charcoal/20 text-campfire-ash'
          }`}
        >
          Медиа по рецензиям
        </button>
        <button
          onClick={() => setActiveTab('reviews-likes')}
          className={`px-4 py-2 text-sm font-medium whitespace-nowrap rounded-full ${
            activeTab === 'reviews-likes' 
              ? 'bg-campfire-amber text-campfire-dark' 
              : 'bg-campfire-charcoal/20 text-campfire-ash'
          }`}
        >
          Рецензии по лайкам
        </button>
        <button
          onClick={() => setActiveTab('users-reviews')}
          className={`px-4 py-2 text-sm font-medium whitespace-nowrap rounded-full ${
            activeTab === 'users-reviews' 
              ? 'bg-campfire-amber text-campfire-dark' 
              : 'bg-campfire-charcoal/20 text-campfire-ash'
          }`}
        >
          Пользователи по рецензиям
        </button>
        <button
          onClick={() => setActiveTab('users-level')}
          className={`px-4 py-2 text-sm font-medium whitespace-nowrap rounded-full ${
            activeTab === 'users-level' 
              ? 'bg-campfire-amber text-campfire-dark' 
              : 'bg-campfire-charcoal/20 text-campfire-ash'
          }`}
        >
          Пользователи по уровню
        </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 MobileRating; 