import React, { useState, useEffect } from 'react';
import { useParams, Link, useNavigate } from 'react-router-dom';
import { pb, getFileUrl } from '../../services/pocketbaseService';
import { FaStar, FaHeart, FaComment, FaEdit, FaTrash, FaFire } from 'react-icons/fa';
import { motion, AnimatePresence } from 'framer-motion';
import { useAuth } from '../../contexts/AuthContext';
import RatingChart from '../../components/reviews/RatingChart';
import ReviewForm from '../components/MobileReviewForm';
import Modal from '../../components/common/Modal';

const MobileMediaOverviewPage = () => {
  const { path } = useParams();
  const { user } = useAuth();
  const navigate = useNavigate();
  const [media, setMedia] = useState(null);
  const [reviews, setReviews] = useState([]);
  const [userReview, setUserReview] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [activeTab, setActiveTab] = useState('overview');
  const [selectedSeasonId, setSelectedSeasonId] = useState(null);
  const [seasons, setSeasons] = useState([]);
  const [selectedSeasonDetails, setSelectedSeasonDetails] = useState(null);
  const [isReviewFormOpen, setIsReviewFormOpen] = useState(false);
  const [isReviewExpanded, setIsReviewExpanded] = useState({});

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

        // Получаем данные медиа
        const mediaData = await pb.collection('media').getFirstListItem(`path="${path}"`, {
          expand: 'poster,backdrop'
        });

        // Получаем рецензии
        const reviewsData = await pb.collection('reviews').getList(1, 50, {
          filter: `media_id="${mediaData.id}"`,
          sort: '-created',
          expand: 'user_id'
        });

        // Если это сериал или аниме, получаем сезоны
        if (mediaData.type === 'tv' || mediaData.type === 'anime') {
          const seasonsData = await pb.collection('seasons').getList(1, 50, {
            filter: `media_id="${mediaData.id}"`,
            sort: 'season_number'
          });
          setSeasons(seasonsData.items);
        }

        // Получаем рецензию пользователя, если он авторизован
        if (user) {
          try {
            const userReviewData = await pb.collection('reviews').getFirstListItem(
              `user_id="${user.id}" && media_id="${mediaData.id}"`
            );
            setUserReview(userReviewData);
          } catch (err) {
            // Если рецензия не найдена, это нормально
            setUserReview(null);
          }
        }

        setMedia(mediaData);
        setReviews(reviewsData.items || []);
      } catch (err) {
        console.error('Error fetching media data:', err);
        if (err.status === 404) {
          setError('Медиа не найдено');
          navigate('/404');
        } else {
          setError('Не удалось загрузить данные');
        }
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, [path, user, navigate]);

  // Функция для загрузки деталей сезона
  const loadSeasonDetails = async (seasonId) => {
    try {
      const seasonData = await pb.collection('seasons').getOne(seasonId);
      setSelectedSeasonDetails(seasonData);
    } catch (err) {
      console.error('Error loading season details:', err);
    }
  };

  // Обработчик изменения сезона
  useEffect(() => {
    if (selectedSeasonId) {
      loadSeasonDetails(selectedSeasonId);
    } else {
      setSelectedSeasonDetails(null);
    }
  }, [selectedSeasonId]);

  // Функция для расчета средних оценок по характеристикам
  const calculateAverageRatings = (reviews) => {
    if (!reviews || !Array.isArray(reviews) || reviews.length === 0) {
      return null;
    }

    const categories = [
      'plot', 'characters', 'visuals', 'soundtrack', 'acting', 'direction',
      'pacing', 'dialogue', 'world_building', 'animation', 'art_style'
    ];

    const averages = {};
    categories.forEach(category => {
      const validRatings = reviews
        .map(review => review.ratings?.[category])
        .filter(rating => rating !== undefined && rating !== null);
      
      if (validRatings.length > 0) {
        averages[category] = validRatings.reduce((sum, rating) => sum + rating, 0) / validRatings.length;
      }
    });

    return averages;
  };

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

  const isOwnMedia = user && media && user.id === media.created_by;
  const averageRatings = calculateAverageRatings(reviews);

  const renderFireRating = (rating) => {
    const maxFires = 10;
    const fires = [];
    const normalizedRating = Math.round((rating / 10) * maxFires);

    for (let i = 0; i < maxFires; i++) {
      fires.push(
        <FaFire
          key={i}
          className={`text-lg ${
            i < normalizedRating ? 'text-campfire-amber' : 'text-campfire-ash/30'
          }`}
        />
      );
    }
    return fires;
  };

  return (
    <div className="min-h-screen bg-campfire-dark">
      {/* Media Header */}
      <div className="relative h-[400px] mb-8">
        <div className="absolute inset-0">
          <img
            src={getFileUrl(media, 'backdrop') || getFileUrl(media, 'poster')}
            alt={media.title}
            className="w-full h-full object-cover"
          />
          <div className="absolute inset-0 bg-gradient-to-t from-campfire-dark via-campfire-dark/80 to-transparent"></div>
        </div>

        <div className="absolute bottom-0 left-0 right-0 p-6">
          <div className="flex items-end gap-4">
            <img
              src={getFileUrl(media, 'poster')}
              alt={media.title}
              className="w-24 h-36 object-cover rounded-lg shadow-lg"
            />
            <div className="flex-1">
              <h1 className="text-2xl font-bold text-campfire-light mb-2">
                {media.title}
              </h1>
              <div className="flex items-center gap-4 text-campfire-ash text-sm">
                <div className="flex items-center">
                  <FaStar className="text-campfire-amber mr-1" />
                  <span>{media.average_rating?.toFixed(1) || '0.0'}</span>
                </div>
                <span>•</span>
                <span>{media.review_count || 0} рецензий</span>
                <span>•</span>
                <span>{media.type}</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Seasons Navigation (if applicable) */}
      {(media.type === 'tv' || media.type === 'anime') && seasons.length > 0 && (
        <div className="px-4 mb-8">
          <div className="flex flex-wrap gap-2">
            <button
              onClick={() => setSelectedSeasonId(null)}
              className={`px-4 py-2 rounded-md text-sm font-medium transition-colors duration-200 ${
                selectedSeasonId === null
                  ? 'bg-campfire-amber text-campfire-dark'
                  : 'bg-campfire-charcoal text-campfire-ash hover:bg-campfire-ash/20'
              }`}
            >
              Общее
            </button>
            {seasons.map(season => (
              <button
                key={season.id}
                onClick={() => setSelectedSeasonId(season.id)}
                className={`px-4 py-2 rounded-md text-sm font-medium transition-colors duration-200 ${
                  selectedSeasonId === season.id
                    ? 'bg-campfire-amber text-campfire-dark'
                    : 'bg-campfire-charcoal text-campfire-ash hover:bg-campfire-ash/20'
                }`}
              >
                Сезон {season.season_number}
              </button>
            ))}
          </div>
        </div>
      )}

      {/* Selected Season Details */}
      {selectedSeasonDetails && (
        <div className="px-4 mb-8">
          <div className="bg-campfire-charcoal/20 backdrop-blur-md border border-campfire-ash/30 rounded-lg p-4">
            <h3 className="text-xl font-bold text-campfire-light mb-2">
              Сезон {selectedSeasonDetails.season_number}
            </h3>
            {selectedSeasonDetails.overview && (
              <p className="text-campfire-light/80 mb-4">{selectedSeasonDetails.overview}</p>
            )}
            <div className="flex items-center gap-4 text-campfire-ash text-sm">
              <div className="flex items-center">
                <FaStar className="text-campfire-amber mr-1" />
                <span>{selectedSeasonDetails.average_rating?.toFixed(1) || '0.0'}</span>
              </div>
              <span>•</span>
              <span>{selectedSeasonDetails.review_count || 0} рецензий</span>
            </div>
          </div>
        </div>
      )}

      {/* Tabs */}
      <div className="px-4 mb-8">
        <div className="flex gap-4 border-b border-campfire-ash/30">
          <button
            onClick={() => setActiveTab('overview')}
            className={`pb-2 px-1 ${
              activeTab === 'overview'
                ? 'text-campfire-amber border-b-2 border-campfire-amber'
                : 'text-campfire-ash hover:text-campfire-light'
            }`}
          >
            Обзор
          </button>
          <button
            onClick={() => setActiveTab('reviews')}
            className={`pb-2 px-1 ${
              activeTab === 'reviews'
                ? 'text-campfire-amber border-b-2 border-campfire-amber'
                : 'text-campfire-ash hover:text-campfire-light'
            }`}
          >
            Рецензии
          </button>
        </div>
      </div>

      {/* Content */}
      <div className="px-4">
        <AnimatePresence mode="wait">
          {activeTab === 'overview' ? (
            <motion.div
              key="overview"
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              exit={{ opacity: 0, y: -20 }}
              className="space-y-6"
            >
              <div>
                <h2 className="text-xl font-bold text-campfire-light mb-2">Описание</h2>
                <p className="text-campfire-light/80">{media.overview}</p>
              </div>

              {media.release_date && (
                <div>
                  <h2 className="text-xl font-bold text-campfire-light mb-2">Дата выхода</h2>
                  <p className="text-campfire-light/80">
                    {new Date(media.release_date).toLocaleDateString()}
                  </p>
                </div>
              )}

              {/* График средних оценок */}
              {(() => {
                if (averageRatings && Object.keys(averageRatings).length > 0) {
                  return (
                    <div className="mt-6">
                      <h3 className="text-campfire-light font-medium mb-4">Средние оценки</h3>
                      <RatingChart 
                        ratings={averageRatings}
                        labels={media.characteristics}
                      />
                    </div>
                  );
                }
                return null;
              })()}
            </motion.div>
          ) : (
            <motion.div
              key="reviews"
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              exit={{ opacity: 0, y: -20 }}
              className="space-y-4"
            >
              {/* Review Form */}
              {user ? (
                <div className="mb-8">
                  {userReview ? (
                    <div className="bg-campfire-charcoal/20 backdrop-blur-md border border-campfire-ash/30 rounded-lg p-4">
                      <h3 className="text-lg font-semibold text-campfire-light mb-2">Ваша рецензия</h3>
                      <div className="flex items-center gap-2 mb-2">
                        <div className="flex items-center text-campfire-amber">
                          <FaStar className="mr-1" />
                          <span>{userReview.rating}</span>
                        </div>
                        <span className="text-campfire-ash">•</span>
                        <span className="text-campfire-ash text-sm">
                          {new Date(userReview.created).toLocaleDateString()}
                        </span>
                      </div>
                      <p className="text-campfire-light/80">{userReview.text}</p>
                      <button
                        onClick={() => setIsReviewFormOpen(true)}
                        className="mt-4 text-campfire-amber hover:underline"
                      >
                        Редактировать
                      </button>
                    </div>
                  ) : (
                    <button
                      onClick={() => setIsReviewFormOpen(true)}
                      className="w-full py-3 bg-campfire-amber text-campfire-dark rounded-lg hover:bg-campfire-amber/80 transition-colors"
                    >
                      Написать рецензию
                    </button>
                  )}
                </div>
              ) : (
                <div className="bg-campfire-charcoal/20 backdrop-blur-md border border-campfire-ash/30 rounded-lg p-4 text-center">
                  <p className="text-campfire-light">
                    <Link to="/auth/login" className="text-campfire-amber hover:underline">
                      Войдите
                    </Link>
                    , чтобы оставить рецензию
                  </p>
                </div>
              )}

              {/* Reviews List */}
              {reviews && Array.isArray(reviews) && reviews.length > 0 ? (
                reviews.map((review) => (
                  <div
                    key={review.id}
                    className="bg-campfire-charcoal/20 backdrop-blur-md border border-campfire-ash/30 rounded-lg p-4"
                  >
                    <div className="flex items-start gap-4">
                      <img
                        src={getFileUrl(review.expand?.user_id, 'profile_picture') || '/default-avatar.png'}
                        alt={review.expand?.user_id?.username}
                        className="w-12 h-12 rounded-full object-cover"
                      />
                      <div className="flex-1">
                        <div className="flex items-center justify-between mb-2">
                          <Link
                            to={`/profile/${review.expand?.user_id?.login}`}
                            className="text-campfire-light font-medium hover:text-campfire-amber"
                          >
                            {review.expand?.user_id?.username}
                          </Link>
                          <div className="flex items-center text-campfire-amber">
                            <FaFire className="mr-1" />
                            <span>{review.ratings?.overall?.toFixed(1) || '0.0'}</span>
                          </div>
                        </div>
                        <p className={`text-campfire-light/80 ${!isReviewExpanded[review.id] && 'line-clamp-3'}`}>
                          {review.text}
                        </p>
                        {review.text && review.text.length > 200 && (
                          <button
                            onClick={() => setIsReviewExpanded(prev => ({
                              ...prev,
                              [review.id]: !prev[review.id]
                            }))}
                            className="mt-2 text-campfire-amber hover:underline"
                          >
                            {isReviewExpanded[review.id] ? 'Свернуть' : 'Развернуть'}
                          </button>
                        )}
                        <div className="flex items-center gap-4 mt-2 text-campfire-ash text-sm">
                          <div className="flex items-center">
                            <FaHeart className="mr-1" />
                            <span>{review.likes?.length || 0}</span>
                          </div>
                          <div className="flex items-center">
                            <FaComment className="mr-1" />
                            <span>{review.comments?.length || 0}</span>
                          </div>
                          <span>•</span>
                          <span>{new Date(review.created).toLocaleDateString()}</span>
                        </div>
                      </div>
                    </div>
                  </div>
                ))
              ) : (
                <div className="text-center py-8 text-campfire-light">
                  Пока нет рецензий
                </div>
              )}
            </motion.div>
          )}
        </AnimatePresence>
      </div>

      {/* Review Form Modal */}
      <Modal
        isOpen={isReviewFormOpen}
        onClose={() => setIsReviewFormOpen(false)}
        title={userReview ? 'Редактировать рецензию' : 'Написать рецензию'}
      >
        <ReviewForm
  mediaId={media.id}
  seasonId={selectedSeasonId}
  mediaType={media.type}
  progress_type={media.progress_type}
  characteristics={media.characteristics}
  existingReview={userReview}
  onEdit={async (reviewId, data) => {
    try {
      await pb.collection('reviews').update(reviewId, data);
      await fetchUserReview();
      setIsReviewFormOpen(false);
    } catch (err) {
      console.error('Error updating review:', err);
    }
  }}
          onSubmit={async (data) => {
            try {
              if (userReview) {
                await pb.collection('reviews').update(userReview.id, data);
              } else {
                await pb.collection('reviews').create({
                  ...data,
                  user_id: user.id,
                  media_id: media.id
                });
              }
              setIsReviewFormOpen(false);
              // Обновляем данные
              const reviewsData = await pb.collection('reviews').getList(1, 50, {
                filter: `media_id="${media.id}"`,
                sort: '-created',
                expand: 'user_id'
              });
              setReviews(reviewsData.items);
            } catch (err) {
              console.error('Error saving review:', err);
            }
          }}
          onDelete={async () => {
            try {
              await pb.collection('reviews').delete(userReview.id);
              setIsReviewFormOpen(false);
              setUserReview(null);
              // Обновляем данные
              const reviewsData = await pb.collection('reviews').getList(1, 50, {
                filter: `media_id="${media.id}"`,
                sort: '-created',
                expand: 'user_id'
              });
              setReviews(reviewsData.items);
            } catch (err) {
              console.error('Error deleting review:', err);
            }
          }}
          seasons={seasons}
          selectedSeasonId={selectedSeasonId}
        />
      </Modal>
    </div>
  );
};

export default MobileMediaOverviewPage; 