import React, { useEffect, useState, useCallback } from 'react'; // Import useCallback
import { useParams } from 'react-router-dom';
import {
  getMediaByPath, // Use getMediaByPath
  getReviewsByMediaId,
  createReview,
  updateReview,
  deleteReview,
  getUserReviewForMedia,
  getFileUrl, // Import getFileUrl
  updateMedia, // Import updateMedia for editing
  getSeasonsByMediaId, // Import getSeasonsByMediaId
  getSeasonById // Import getSeasonById
} from '../services/pocketbaseService';
import { useAuth } from '../contexts/AuthContext';
import ReviewForm from '../components/reviews/ReviewForm';
import ReviewList from '../components/reviews/ReviewList';
import RatingChart from '../components/reviews/RatingChart';
import { FaFire, FaEdit } from 'react-icons/fa'; // Import FaEdit icon
import Modal from '../components/common/Modal'; // Import Modal
import MediaForm from '../components/admin/MediaForm'; // Import MediaForm
import { toast } from 'react-hot-toast';

const MediaOverviewPage = () => { // Renamed component
  // Get the 'path' parameter from the URL
  const { path } = useParams();
  const { user, userProfile } = useAuth(); // Get user and userProfile for permissions
  const [media, setMedia] = useState(null);
  const [reviews, setReviews] = useState([]);
  const [userReview, setUserReview] = useState(null); // State for the current user's review
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  // Initialize reviewCharacteristics from media.characteristics or use a default
  const [reviewCharacteristics, setReviewCharacteristics] = useState({});

  const [isEditModalOpen, setIsEditModalOpen] = useState(false); // State for edit modal

  // New state for seasons
  const [seasons, setSeasons] = useState([]);
  // State to track which season's reviews are currently displayed (null for overall)
  const [selectedSeasonId, setSelectedSeasonId] = useState(null);
  // New state for the currently selected season's details
  const [selectedSeasonDetails, setSelectedSeasonDetails] = useState(null);


  // Check if the current user is admin or critic
  const isAdminOrCritic = userProfile && (userProfile.role === 'admin' || userProfile.is_critic === true);

  // Determine if the media type supports seasons
  const supportsSeasons = media?.type === 'tv' || media?.type === 'anime';


  // Use useCallback for loadMediaAndSeasons
  const loadMediaAndSeasons = useCallback(async () => {
      try {
          setLoading(true); // Start loading for media/seasons
          setError(null);
          console.log('MediaOverviewPage: Effect 1 - Loading media for path:', path); // Renamed log

          const mediaData = await getMediaByPath(path);
          if (!mediaData) {
              throw new Error('Медиа не найдено');
          }
          setMedia(mediaData);
          console.log('MediaOverviewPage: Effect 1 - Media data loaded and set to state:', mediaData); // Renamed log

          // Use characteristics from the fetched media data, or a default if not available
          const characteristics = mediaData.characteristics && typeof mediaData.characteristics === 'object'
              ? mediaData.characteristics
              : { overall: 'Общая оценка' }; // Fallback default
          setReviewCharacteristics(characteristics);

          // If media supports seasons, fetch seasons
          if (mediaData.type === 'tv' || mediaData.type === 'anime') {
              const seasonsData = await getSeasonsByMediaId(mediaData.id);
              // Sort seasons by season_number
              seasonsData.sort((a, b) => a.season_number - b.season_number);
              setSeasons(seasonsData || []);
              console.log('MediaOverviewPage: Effect 1 - Seasons loaded:', seasonsData); // Renamed log
          } else {
              setSeasons([]); // Clear seasons if media type doesn't support them
          }

          // Set initial selected season to null (overall reviews)
          // This will trigger Effect 2 to load overall reviews
          setSelectedSeasonId(null); // Reset selected season on media change
          setSelectedSeasonDetails(null); // Clear season details

      } catch (err) {
          console.error("Error loading media or seasons:", err);
          setError("Не удалось загрузить контент или сезоны");
          setLoading(false); // Ensure loading is false on error
      }
  }, [path]); // Depend on path to refetch if path changes


  // Effect 1: Load media and seasons when path changes
  useEffect(() => {
      if (path) {
          loadMediaAndSeasons();
      }
  }, [path, loadMediaAndSeasons]); // Depend on path and the memoized loadMediaAndSeasons


  // Function to load reviews
  const loadReviews = useCallback(async () => {
      if (!media?.id) return; // Don't proceed if media is not loaded

       try {
           setError(null); // Clear previous errors

           console.log('MediaOverviewPage: Effect 2 - Loading reviews for media ID:', media.id, 'and season ID:', selectedSeasonId); // Renamed log
           console.log('MediaOverviewPage: Effect 2 - Current user ID:', user?.id); // Renamed log // Log current user ID

          // Если выбран сезон, загружаем рецензии только для него
          // Если выбран "Общее", загружаем все рецензии для всех сезонов
          const reviewsData = selectedSeasonId 
              ? await getReviewsByMediaId(media.id, selectedSeasonId)
              : await getReviewsByMediaId(media.id, null, true); // Добавляем параметр для загрузки всех рецензий

           setReviews(reviewsData || []);
           console.log('MediaOverviewPage: Effect 2 - Reviews loaded:', reviewsData); // Renamed log

           // Fetch the current user's review if logged in, for the selected media/season
           if (user) {
             console.log('MediaOverviewPage: Effect 2 - Fetching user review for user ID:', user.id, 'media ID:', media.id, 'and season ID:', selectedSeasonId); // Renamed log
             const userReviewData = await getUserReviewForMedia(user.id, media.id, selectedSeasonId);
             setUserReview(userReviewData);
             console.log('MediaOverviewPage: Effect 2 - User review fetched:', userReviewData); // Renamed log
           } else {
             setUserReview(null); // Ensure userReview is null if not logged in
             console.log('MediaOverviewPage: Effect 2 - User not logged in, skipping user review fetch.'); // Renamed log
           }

       } catch (err) {
           console.error("Error loading reviews:", err);
           setError("Не удалось загрузить рецензии");
       } finally {
           // Set loading false only if media is also loaded (handled by Effect 1)
           // Ensure loading is false after reviews are loaded, regardless of media loading state
           setLoading(false);
       }
   }, [media?.id, selectedSeasonId, user]); // Depend on media.id, selectedSeasonId, and user


  // Effect 2: Load reviews when media ID or selectedSeasonId changes
  useEffect(() => {
      loadReviews();
  }, [media?.id, selectedSeasonId, user, loadReviews]); // Depend on media.id, selectedSeasonId, user, and the memoized loadReviews


  // Effect 3: Load selected season details when selectedSeasonId changes
  useEffect(() => {
      const loadSeasonDetails = async () => {
          if (selectedSeasonId) {
              try {
                  console.log('MediaOverviewPage: Effect 3 - Loading season details for ID:', selectedSeasonId); // Renamed log
                  const seasonData = await getSeasonById(selectedSeasonId);
                  setSelectedSeasonDetails(seasonData);
                  console.log('MediaOverviewPage: Effect 3 - Season details loaded:', seasonData); // Renamed log
              } catch (err) {
                  console.error("Error loading season details:", err);
                  setSelectedSeasonDetails(null); // Clear details on error
              }
          } else {
              setSelectedSeasonDetails(null); // Clear details if overall is selected
          }
      };

      loadSeasonDetails();
  }, [selectedSeasonId]); // Depend on selectedSeasonId


  // Log media state whenever it changes
  useEffect(() => {
      console.log('MediaOverviewPage: Media state updated:', media); // Renamed log
      if (media) {
          console.log('MediaOverviewPage: Media state stats:', { average_rating: media.average_rating, review_count: media.review_count }); // Renamed log
      }
  }, [media]);


  // Function to reload reviews and user review after an action (create, edit, delete)
  const reloadReviewsAndUserReview = useCallback(async () => {
      if (!media?.id) return;
      try {
          console.log('MediaOverviewPage: Reloading reviews after action...'); // Renamed log
          const reviewsData = await getReviewsByMediaId(media.id, selectedSeasonId);
          setReviews(reviewsData || []);
          if (user) {
              const userReviewData = await getUserReviewForMedia(user.id, media.id, selectedSeasonId);
              setUserReview(userReviewData);
          } else {
              setUserReview(null);
          }
          // Also reload media data to get updated overall stats
          const updatedMediaData = await getMediaByPath(path);
          if (updatedMediaData) {
              setMedia(updatedMediaData);
              // No need to update characteristics here, they are static per media
          }

      } catch (err) {
          console.error("Error reloading data after action:", err);
      }
  }, [media?.id, selectedSeasonId, user, path]); // Depend on media.id, selectedSeasonId, user, and path


  const handleReviewSubmit = async (reviewData) => {
    try {
      // Use the media ID from the state and the season ID from the form (reviewData.season_id)
      // The createReview function now adds the user_id internally
      await createReview({ ...reviewData, media_id: media.id }); // Pass media_id explicitly
      console.log('MediaOverviewPage: Review submitted successfully. Reloading data...'); // Renamed log
      // Refresh data after submission
      setTimeout(() => {
        reloadReviewsAndUserReview();
      }, 300); // 300ms delay
    } catch (error) {
      console.error('Error submitting review:', error);
      // Handle error (e.g., show a message to the user)
    }
  };

  const handleReviewEdit = async (reviewId, reviewData) => {
     try {
      // Use the media ID from the state and the season ID from the form (reviewData.season_id)
      await updateReview(reviewId, { ...reviewData, media_id: media.id }); // Pass media_id explicitly
      console.log('MediaOverviewPage: Review edited successfully. Reloading data...'); // Renamed log
      // Refresh data after edit
      setTimeout(() => {
         reloadReviewsAndUserReview();
      }, 300); // 300ms delay
    } catch (error) {
      console.error('Error editing review:', error);
      // Handle error
    }
  };

  const handleReviewDelete = async (reviewId) => {
     try {
      // Use the media ID from the state
      await deleteReview(reviewId, media.id); // deleteReview only needs reviewId, mediaId is optional
      console.log('MediaOverviewPage: Review deleted successfully. Reloading data...'); // Renamed log
      // Refresh data after delete
      setTimeout(() => {
         reloadReviewsAndUserReview();
      }, 300); // 300ms delay
    } catch (error) {
      console.error('Error deleting review:', error);
      // Handle error
    }
  };

  // Handle media edit submission from the modal
  const handleMediaEditSubmit = async (formData) => {
    try {
      setLoading(true);
      const response = await updateMedia(media.id, formData);
      setMedia(response);
      setIsEditModalOpen(false);
      toast.success('Контент успешно обновлен');
    } catch (error) {
      console.error('Error updating media:', error);
      let errorMessage = 'Произошла ошибка при обновлении контента';
      
      if (error.response?.data) {
        const data = error.response.data;
        if (typeof data === 'object') {
          const errors = Object.entries(data)
            .map(([field, error]) => `${field}: ${error.message || error}`)
            .join(', ');
          errorMessage = errors || errorMessage;
        }
      }
      
      toast.error(errorMessage);
    } finally {
      setLoading(false);
    }
  };


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

  if (!media) {
    return (
      <div className="min-h-screen bg-campfire-dark pt-20 flex justify-center items-center">
        <div className="text-campfire-ash text-lg">Медиа не найдено.</div>
      </div>
    );
  }

  // Calculate average ratings for the chart from all reviews
  // This calculation is still needed for the detailed characteristic chart
  const aggregateRatings = reviews.reduce((acc, review) => {
    // Use review.ratings if available, otherwise fallback to overall_rating
    // Now review.ratings is expected to be { [key]: number }
    const ratingsToAggregate = review.ratings && typeof review.ratings === 'object' && Object.keys(review.ratings).length > 0
        ? review.ratings
        : { overall: review.overall_rating }; // Adapt fallback


    Object.entries(ratingsToAggregate).forEach(([key, ratingValue]) => {
      // Only include numeric values that correspond to a characteristic key
      if (reviewCharacteristics.hasOwnProperty(key) && typeof ratingValue === 'number' && ratingValue >= 1 && ratingValue <= 10) {
        if (!acc[key]) {
          acc[key] = { total: 0, count: 0 };
        }
        acc[key].total += ratingValue;
        acc[key].count += 1;
      } else {
         // console.warn(`Invalid rating data found for key "${key}" in review ${review.id}:`, ratingValue);
      }
    });

    return acc;
  }, {});

  const averageRatingsForChart = Object.entries(aggregateRatings).reduce((acc, [key, data]) => {
    // Only include characteristics that are defined in the media's characteristics
    if (reviewCharacteristics[key]) {
        acc[key] = data.count > 0 ? parseFloat((data.total / data.count).toFixed(2)) : 0; // Calculate average and fix to 2 decimal places
    }
    return acc;
  }, {});

  console.log('MediaOverviewPage: Rendering. Current media state:', media); // Renamed log // Log state before render
  console.log('MediaOverviewPage: Rendering. Current selectedSeasonDetails state:', selectedSeasonDetails); // Renamed log // Log season details state


  return (
    <div className="min-h-screen bg-campfire-dark"> {/* Добавляем отступ сверху */}
      {/* Hero Section */}
      <div
        className="relative h-[666px] w-full bg-cover bg-center bg-no-repeat"
        style={{ 
          backgroundImage: `url(${getFileUrl(media, 'backdrop')})`,
          backgroundSize: 'cover',
          backgroundPosition: 'top', // Смещаем изображение немного вниз
          backgroundRepeat: 'no-repeat'
        }}
      >
        {/* Gradient Overlay */}
        <div className="absolute inset-0 bg-gradient-to-t from-campfire-dark via-campfire-dark/80 to-transparent"></div>
        
        {/* Content */}
        <div className="container-custom relative z-10 h-full flex items-end pb-12">
          <div className="flex items-center">
            <img
              src={getFileUrl(media, 'poster')}
              alt={media.title}
              className="w-32 md:w-48 rounded-lg shadow-xl mr-8 object-cover"
            />
            <div>
              <h1 className="text-4xl md:text-5xl font-bold text-campfire-light mb-4">
                {media.title}
              </h1>
              <div className="flex items-center text-campfire-ash text-lg mb-4">
                <span className="text-campfire-amber mr-4 text-2xl font-bold">
                  {media.average_rating ? parseFloat(media.average_rating).toFixed(1) : 'N/A'} / 10
                </span>
                <FaFire className="text-campfire-amber mr-4 text-xl" />
                <span className="text-campfire-ash text-lg mr-4">
                  {media.review_count || 0} рецензий
                </span>
                {media.release_date && (
                  <span className="text-campfire-ash text-lg">
                    Дата выхода: {new Date(media.release_date).toLocaleDateString()}
                  </span>
                )}
              </div>
            </div>
          </div>
        </div>
      </div>

      <div className="container-custom py-12">
        {/* Overview and Details */}
        <div className="mb-12">
           <h2 className="text-2xl font-bold text-campfire-light mb-4">Обзор</h2>
           <p className="text-campfire-ash leading-relaxed">
             {media.overview || media.description || 'Описание отсутствует.'}
           </p>
           {/* Add more details here if available in media object */}
           {/* <div className="mt-6 text-campfire-ash">
             <p><strong>Тип:</strong> {media.type === 'movie' ? 'Фильм' : media.type === 'tv' ? 'Сериал' : 'Игра'}</p>
             <p><strong>Дата выхода:</strong> {new Date(media.release_date).toLocaleDateString()}</p>
           </div> */}
        </div>

        {/* Edit Media Button (Visible only to Admin/Critic) */}
        {isAdminOrCritic && media && (
            <div className="flex justify-end mb-8"> {/* Added margin bottom */}
                <button
                    onClick={() => setIsEditModalOpen(true)}
                    className="btn-secondary flex items-center space-x-2"
                >
                    <FaEdit size={18} />
                    <span>Редактировать медиа</span>
                </button>
            </div>
        )}

        {/* Seasons Navigation (if media supports seasons and has seasons) */}
        {supportsSeasons && seasons.length > 0 && (
            <div className="mb-8">
                <h3 className="text-xl font-bold text-campfire-light mb-4">Сезоны</h3>
                <div className="flex flex-wrap gap-2">
                    {/* Button for overall reviews */}
                    <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>
                    {/* Buttons for each season */}
                    {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} {season.title ? ` - ${season.title}` : ''}
                        </button>
                    ))}
                </div>
            </div>
        )}

        {/* Selected Season Details (if a season is selected) */}
        {selectedSeasonDetails && (
            <div className="mb-12 p-6 bg-campfire-charcoal rounded-lg shadow-md border border-campfire-ash/20">
                <h3 className="text-2xl font-bold text-campfire-light mb-4">
                    Сезон {selectedSeasonDetails.season_number} {selectedSeasonDetails.title ? `- ${selectedSeasonDetails.title}` : ''}
                </h3>
                <div className="flex items-start">
                    {selectedSeasonDetails.poster && (
                        <img
                            src={getFileUrl(selectedSeasonDetails, 'poster')}
                            alt={`Постер сезона ${selectedSeasonDetails.season_number}`}
                            className="w-24 md:w-32 rounded-md shadow-lg mr-6 object-cover border border-campfire-ash/30"
                        />
                    )}
                    <div>
                        {selectedSeasonDetails.overview && (
                            <p className="text-campfire-ash leading-relaxed mb-4">
                                {selectedSeasonDetails.overview}
                            </p>
                        )}
                        {selectedSeasonDetails.release_date && (
                            <p className="text-campfire-ash text-sm">
                                Дата выхода: {new Date(selectedSeasonDetails.release_date).toLocaleDateString()}
                            </p>
                        )}
                         {/* Display season rating and review count */}
                         <div className="flex items-center text-campfire-ash text-sm mt-2">
                            <span className="text-campfire-amber mr-2 font-bold">
                                {selectedSeasonDetails.average_rating !== null && selectedSeasonDetails.average_rating !== undefined && !isNaN(parseFloat(selectedSeasonDetails.average_rating)) ? parseFloat(selectedSeasonDetails.average_rating).toFixed(1) : 'N/A'} / 10
                            </span>
                            <FaFire className="text-campfire-amber mr-2 text-base" />
                            <span>
                                {selectedSeasonDetails.review_count !== null && selectedSeasonDetails.review_count !== undefined && !isNaN(parseInt(selectedSeasonDetails.review_count)) ? parseInt(selectedSeasonDetails.review_count) : 0} рецензий
                            </span>
                         </div>
                    </div>
                </div>
            </div>
        )}


        {/* Review Section */}
        <div className="mb-12">
          <h2 className="text-2xl font-bold text-campfire-light mb-6 border-b border-campfire-ash/20 pb-4">
             Рецензии {selectedSeasonId === null ? ' (Общие)' : ` (Сезон ${seasons.find(s => s.id === selectedSeasonId)?.season_number || ''})`}
          </h2>

          {/* Average Rating Chart */}
          {reviews.length > 0 && Object.keys(averageRatingsForChart).length > 0 && ( // Only show chart if there are reviews and applicable ratings
             <div className="mb-8 bg-campfire-charcoal rounded-lg shadow-md p-6">
                <h3 className="text-xl font-bold text-campfire-light mb-4 text-center">Средние оценки по характеристикам</h3>
                <div className="max-w-md mx-auto">
                   {/* Pass calculated average ratings and characteristics labels */}
                   <RatingChart ratings={averageRatingsForChart} labels={reviewCharacteristics} size="large" />
                </div>
             </div>
          )}


          {/* Review Form (Create/Edit/Delete) */}
          {user ? (
            <ReviewForm
              mediaId={media.id} // Pass the media ID
              seasonId={selectedSeasonId} // Pass the selected season ID
              mediaType={media.type} // Pass the media type
              progressType={media.progress_type} // Pass the media's progress type
              characteristics={reviewCharacteristics} // Pass dynamic characteristics
              onSubmit={handleReviewSubmit}
              onEdit={handleReviewEdit}
              onDelete={handleReviewDelete}
              existingReview={userReview} // Pass the user's existing review
              seasons={seasons} // Pass seasons to the form for season selection
              selectedSeasonId={selectedSeasonId} // Pass selected season ID to form
            />
          ) : (
            <div className="bg-campfire-charcoal rounded-lg shadow-md p-6 text-center">
              <p className="text-campfire-light">
                <a href="/auth/login" className="text-campfire-amber hover:underline">Войдите</a>, чтобы оставить рецензию.
              </p>
            </div>
          )}

          {/* Review List */}
          {/* Pass reviewCharacteristics to ReviewList */}
          <ReviewList reviews={reviews} reviewCharacteristics={reviewCharacteristics} />
        </div>
      </div>

      {/* Edit Media Modal */}
      {media && ( // Only render modal if media data is loaded
          <Modal
              isOpen={isEditModalOpen}
              onClose={() => setIsEditModalOpen(false)}
              title={`Редактировать: ${media.title}`}
              size="lg" // Use large size for the modal
          >
              {/* Pass the current media object to MediaForm for editing */}
              <MediaForm
                  media={media} // Pass the media object to pre-fill the form
                  onSuccess={handleMediaEditSubmit} // Handle the update logic
                  onCancel={() => setIsEditModalOpen(false)} // Close modal on cancel
                  isEditing={true} // Indicate that the form is in editing mode
              />
          </Modal>
      )}

    </div>
  );
};

export default MediaOverviewPage; // Renamed export
