import React, { useEffect, useState } from 'react';
import { useParams } from 'react-router-dom';
import { listMedia } from '../services/pocketbaseService'; // Import listMedia
import TiltedCard from '../components/reactbits/Components/TiltedCard/TiltedCard'; // Import TiltedCard
import { useAuth } from '../contexts/AuthContext'; // Import useAuth

const DiscoverPage = () => {
  const { type } = useParams();
  const [pageTitle, setPageTitle] = useState('');
  const [mediaList, setMediaList] = useState([]); // State for media list
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const { userProfile } = useAuth(); // Get userProfile from auth context

  useEffect(() => {
    // Set page title based on the 'type' parameter
    let title = '';
    switch (type) {
      case 'movie': // Changed from 'movies' to 'movie' to match Supabase type
        title = 'Фильмы';
        break;
      case 'tv':
        title = 'Сериалы';
        break;
      case 'game': // Changed from 'games' to 'game' to match Supabase type
        title = 'Игры';
        break;
      case 'anime': // Added case for Anime
        title = 'Аниме';
        break;
      default:
        title = 'Неизвестный тип';
        break;
    }
    setPageTitle(title);

    // Fetch media based on type
    const fetchMedia = async () => {
      try {
        setLoading(true);
        setError(null);
        console.log(`Attempting to fetch media for type: ${type}`); // Added logging
        // Use listMedia to fetch data filtered by type
        // listMedia now returns data with average_rating and review_count
        // Pass the current user to listMedia for permission checks if needed
        // Pass the type filter
        // Default sort for discover pages could be by creation date or title
        const { data } = await listMedia(type, 1, 20, userProfile, null, true, '-created'); // Pass type filter, userProfile, only published, default sort

        console.log('Successfully fetched media:', data); // Added logging
        // The data from listMedia is already formatted with average_rating and review_count
        setMediaList(data);
      } catch (err) {
        console.error('Error fetching media list:', err);
         // Check if the error is a ClientResponseError and provide specific message if possible
        if (err.response && err.response.message) {
             setError(`Ошибка загрузки: ${err.response.message}`);
        } else {
             setError('Не удалось загрузить список медиа');
        }
      } finally {
        setLoading(false);
      }
    };

    if (type) {
      fetchMedia();
    } else {
      // Handle case where type is not provided (e.g., /discover)
      setLoading(false);
      setMediaList([]);
    }

  }, [type, userProfile]); // Re-run effect when type or userProfile changes

  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 (
    // Added min-h-screen and bg-campfire-dark to ensure dark background
    <div className="min-h-screen bg-campfire-dark pt-20 container-custom py-8"> {/* Added bg-campfire-dark */}
      <h1 className="text-3xl font-bold mb-6 text-campfire-light">Раздел: {pageTitle}</h1>

      {mediaList.length > 0 ? (
        <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-8 md:gap-20">
          {mediaList.map((mediaItem) => (
            <TiltedCard 
              key={mediaItem.id} 
              imageSrc={mediaItem.poster_path} 
              captionText={mediaItem.title}
              rating={mediaItem.rating}
              releaseDate={mediaItem.release_date}
            />
          ))}
        </div>
      ) : (
        <p className="text-campfire-ash">
          Пока нет медиа в этом разделе.
        </p>
      )}
    </div>
  );
};

export default DiscoverPage;
