import React, { useEffect, useState } from 'react';
import Marquee from 'react-fast-marquee';
import { getLatestReviews, getFileUrl } from '../services/pocketbaseService'; // Assuming getLatestReviews exists
import { FaFire, FaUserCircle } from 'react-icons/fa'; // Import FaUserCircle
import { Link } from 'react-router-dom'; // Import Link

// Mapping for status values
const statusLabels = {
  not_started: 'Не начато',
  in_progress: 'В процессе',
  completed: 'Завершено',
};

const LatestReviewsMarquee = () => {
  const [reviews, setReviews] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    const fetchReviews = async () => {
      try {
        setLoading(true);
        setError(null);
        // Ensure expand=users,media is included to get related data
        const latestReviews = await getLatestReviews({ expand: 'users,media', sort: '-created', limit: 20 }); // Fetch latest 20 reviews, sorted by creation date descending
        setReviews(latestReviews);
        console.log('LatestReviewsMarquee: Fetched reviews with expand:', latestReviews);
      } catch (err) {
        console.error('Error fetching latest reviews:', err);
        setError('Не удалось загрузить последние рецензии.');
      } finally {
        setLoading(false);
      }
    };

    fetchReviews();
  }, []); // Empty dependency array means this runs once on mount

  if (loading) {
    return <div className="text-campfire-ash text-center py-4">Загрузка последних рецензий...</div>;
  }

  if (error) {
    return <div className="text-status-error text-center py-4">{error}</div>;
  }

  if (!reviews || reviews.length === 0) {
    return <div className="text-campfire-ash text-center py-4">Пока нет последних рецензий.</div>;
  }

  return (
    <div className="bg-campfire-charcoal py-4">
      <Marquee gradient={false} speed={40} pauseOnHover={true}>
        {reviews.map(review => {
          // Add robust checks for expanded data
          const user = review.expand?.users;
          const media = review.expand?.media;

          // Skip review if essential expanded data is missing
          if (!user || !media || typeof media.characteristics !== 'object') {
            console.warn("Skipping review", review.id, "in marquee due to missing user, media, or required fields.");
            return null; // Skip rendering this review
          }

          const username = user.username || 'Анонимный пользователь';
          const avatarUrl = user.profile_picture ? getFileUrl(user, 'profile_picture', { thumb: '40x40' }) : null;
          const userProfileLink = user.login ? `/profile/${user.login}` : '#';

          const mediaTitle = media.title || 'Неизвестное произведение';
          const mediaLink = media.path ? `/media/${media.path}` : '#';

          // Calculate average rating for this specific review based on media characteristics
          const characteristics = media.characteristics;
          const ratings = review.ratings; // Expecting { [key]: number }

          const applicableRatings = Object.entries(characteristics).reduce((acc, [key, label]) => {
              // Check if the rating exists for this characteristic key and is a valid number
              if (ratings && typeof ratings[key] === 'number' && ratings[key] >= 1 && ratings[key] <= 10) {
                  acc.push(ratings[key]);
              }
              return acc;
          }, []);

          const totalApplicableRating = applicableRatings.reduce((sum, value) => sum + value, 0);
          const averageReviewRating = applicableRatings.length > 0
            ? (totalApplicableRating / applicableRatings.length).toFixed(1)
            : 'N/A'; // Show N/A if no applicable ratings


          return (
            <div key={review.id} className="flex items-center bg-campfire-dark rounded-md p-3 mr-6 shadow-sm">
              {/* User Avatar */}
              {avatarUrl ? (
                 <img
                    src={avatarUrl}
                    alt={`${username}'s avatar`}
                    className="w-8 h-8 rounded-full object-cover mr-3 border border-campfire-ash/30"
                 />
              ) : (
                 <FaUserCircle className="w-8 h-8 text-campfire-ash mr-3" />
              )}

              {/* Review Info */}
              <div className="flex flex-col">
                <div className="flex items-center text-sm">
                  {/* Link to user profile */}
                  <Link to={userProfileLink} className="font-semibold text-campfire-light hover:underline mr-1">
                    {username}
                  </Link>
                  <span className="text-campfire-ash mr-1">рецензирует</span>
                  {/* Link to media page */}
                  <Link to={mediaLink} className="font-semibold text-campfire-amber hover:underline">
                    {mediaTitle}
                  </Link>
                </div>
                {/* Display overall average for this review */}
                <div className="flex items-center text-campfire-ash text-xs mt-1">
                   Оценка:
                   <span className="text-campfire-amber ml-1 mr-1">
                      {averageReviewRating} / 10
                   </span>
                   {averageReviewRating !== 'N/A' && <FaFire className="text-campfire-amber" size={12} />}
                </div>
                 {/* Status */}
                {review.status && statusLabels[review.status] && (
                   <div className="mt-1 text-xs text-campfire-ash">
                      Статус: <span className="font-medium text-campfire-light">{statusLabels[review.status]}</span>
                   </div>
                )}
              </div>
            </div>
          );
        })}
      </Marquee>
    </div>
  );
};

export default LatestReviewsMarquee;
