import React, { memo } from 'react';
import { Link } from 'react-router-dom';
import { FaFire } from 'react-icons/fa'; // Changed FaStar to FaFire
import { getFileUrl } from '../../services/pocketbaseService'; // Corrected import path
import { useEffect } from 'react'; // Import useEffect for logging
import { useAuth } from '../../contexts/AuthContext'; // Import useAuth
import LazyImage from '../common/LazyImage';

// MediaCard component displays a card for a media item.
// It now accepts averageRating and reviewCount props from the parent.
// Added userProfile prop to check admin/critic role
const MediaCard = memo(function MediaCard({ media, userProfile }) {
  // Destructure media properties, including the new ones from Supabase
  // Use 'path' for the link instead of 'id'
  // Используем 'poster' вместо 'poster_url' для имени файла
  const { id, title, poster, average_rating, review_count, release_date, type, path, is_published } = media; // Added is_published

  // Используем getFileUrl для получения URL постера
  const posterUrl = getFileUrl(media, 'poster'); // Используем имя поля 'poster'
  const releaseDate = release_date;
  const averageRating = average_rating; // This is the 10-point average from Supabase
  const reviewCount = review_count;

  // Use the 'path' field for the link
  const mediaLink = path ? `/media/${path}` : `/media/${id}`; // Fallback to id if path is missing (for old data)

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


  // Add log to check average_rating and review_count here when component mounts or media prop changes
  useEffect(() => {
      console.log(`MediaCard for "${title}" rendered with media prop:`, media);
      console.log(`MediaCard for "${title}" stats:`, {
        average_rating: averageRating,
        review_count: reviewCount,
        is_published: is_published
      });
  }, [media]);


  return (
    <Link to={mediaLink} className="block">
      <div className="card group h-full bg-campfire-charcoal rounded-lg overflow-hidden shadow-lg border border-campfire-ash/20 transition-all duration-300 hover:shadow-xl hover:border-campfire-amber/30 relative"> {/* Added relative for absolute positioning */}
        <div className="relative overflow-hidden aspect-[2/3]">
          {/* Используем posterUrl, полученный через getFileUrl */}
          <LazyImage
            src={posterUrl}
            alt={title}
            className="w-full h-full transform group-hover:scale-105 transition-transform duration-300"
          />
          {/* Display average rating and review count */}
          {/* Проверяем, что average_rating не null и не undefined перед отображением */}
          {/* Ensure average_rating is treated as a number */}
          {average_rating !== null && average_rating !== undefined && !isNaN(parseFloat(average_rating)) && (
             <div className="absolute top-2 right-2 bg-campfire-dark bg-opacity-75 rounded-full px-2 py-1 flex items-center">
               <FaFire className="text-campfire-amber mr-1" size={14} /> {/* Changed FaStar to FaFire */}
               <span className="text-sm font-medium text-campfire-light">
                 {/* Форматируем average_rating до одной десятичной */}
                 {parseFloat(average_rating).toFixed(1)} / 10
               </span>
               {/* Optionally display review count */}
               {/* {review_count !== null && review_count !== undefined && (
                 <span className="text-xs text-campfire-ash ml-1">({review_count})</span>
               )} */}
             </div>
          )}

          {/* Admin/Critic mark for unpublished media */}
          {isAdminOrCritic && !is_published && (
              <div className="absolute bottom-2 left-2 bg-red-600 bg-opacity-75 text-white text-xs font-semibold px-2 py-1 rounded-full">
                  Не опубликовано
              </div>
          )}

        </div>
        <div className="p-4">
          <h3 className="font-bold text-campfire-light line-clamp-1 mb-1 group-hover:text-campfire-amber transition-colors">
            {title}
          </h3>
          <div className="text-sm text-campfire-ash">
            {releaseDate ? new Date(releaseDate).getFullYear() : 'N/A'}
          </div>
        </div>
      </div>
    </Link>
  );
});

export default MediaCard;
