import { useState } from 'react';
import { Link } from 'react-router-dom';
import { FaThumbsUp, FaComment, FaShare } from 'react-icons/fa';
import RatingChart from './RatingChart';

// Accept characteristics prop
function ReviewCard({ review, isDetailed = false, characteristics }) {
  const [isExpanded, setIsExpanded] = useState(false);

  const {
    id,
    users, // Changed from user to users
    content,
    ratings,
    likes,
    comments,
    created_at,
    spoiler
  } = review;

  // Use users object and rename for clarity
  const userProfile = users;

  // Format date
  const formattedDate = new Date(created_at).toLocaleDateString('ru-RU', {
    year: 'numeric',
    month: 'short',
    day: 'numeric'
  });

  // Calculate overall rating
  const overallRating = Object.values(ratings).reduce((sum, rating) => sum + rating, 0) / Object.keys(ratings).length;

  // Handle content length
  const isLongContent = content.length > 300;
  const displayContent = isLongContent && !isExpanded ? `${content.substring(0, 280)}...` : content;

  return (
    <div className={`bg-campfire-charcoal rounded-lg shadow-lg p-6 mb-6 ${isDetailed ? 'border border-campfire-ash' : ''}`}>
      {/* Review Header */}
      <div className="flex justify-between items-start mb-4">
        <div className="flex items-center">
          <Link to={`/profile/${userProfile?.login}`}> {/* Use userProfile?.id */}
            <img
              src={userProfile?.profile_picture || 'https://questhowth.ie/wp-content/uploads/2018/04/user-placeholder.png'} // Use userProfile?.profile_picture
              alt={userProfile?.username} // Use userProfile?.username
              className="w-10 h-10 rounded-full object-cover mr-3"
            />
          </Link>
          <div>
            <Link to={`/profile/${userProfile?.login}`} className="font-medium text-campfire-light hover:text-campfire-amber"> {/* Use userProfile?.id */}
              {userProfile?.username} {/* Use userProfile?.username */}
            </Link>
            {userProfile?.is_critic && ( // Use userProfile?.is_critic
              <span className="ml-2 inline-block px-2 py-0.5 text-xs font-medium bg-campfire-amber text-campfire-dark rounded-full">
                Critic
              </span>
            )}
            <div className="text-sm text-campfire-ash">{formattedDate}</div>
          </div>
        </div>
        <div className="flex items-center">
          <span className="inline-flex items-center justify-center w-10 h-10 rounded-full bg-campfire-amber text-campfire-dark font-bold">
            {overallRating.toFixed(1)}
          </span>
        </div>
      </div>

      {/* Review Content */}
      {/* Ensure grid is applied on md screens when detailed */}
      {/* Changed grid-cols-3 to grid-cols-2 for 2 columns */}
      <div className={`grid grid-cols-1 gap-8 ${isDetailed ? 'md:grid md:grid-cols-2' : ''}`}>
        {/* Text Content */}
        {/* Changed col-span-2 to col-span-1 for 2 columns */}
        {/* Removed overflow-hidden, kept break-words */}
        <div className={`${isDetailed ? 'md:col-span-1 break-words' : ''}`}>
          {/* Spoiler Warning */}
          {spoiler && (
            <div className="bg-status-warning bg-opacity-20 text-status-warning p-3 rounded-md mb-4">
              <span className="font-bold">Spoiler Warning:</span> This review contains spoilers.
            </div>
          )}

          {/* Review Text */}
          <p className="text-campfire-light mb-4">
            {displayContent}
          </p>

          {/* Expand/Collapse for long content */}
          {isLongContent && (
            <button
              onClick={() => setIsExpanded(!isExpanded)}
              className="text-campfire-amber hover:text-campfire-ember mb-4 text-sm font-medium"
            >
              {isExpanded ? 'Show Less' : 'Read More'}
            </button>
          )}
        </div>

        {/* Rating Chart */}
        {/* Ensure chart takes 1 column on md screens when detailed */}
        {/* Added flex, justify-center, items-center to center the chart */}
        <div className={`${isDetailed ? 'md:col-span-1 flex justify-center items-center' : 'hidden md:flex md:justify-center md:items-center'}`}>
          <RatingChart
            ratings={ratings}
            // Pass characteristics as labels to RatingChart
            labels={characteristics}
            size={isDetailed ? 'big' : 'medium'} // Reverted size to 'big' for detailed view
            showLegend={isDetailed}
            isDetailed={isDetailed} // Ensure prop is passed
          />
        </div>
      </div>

      {/* Review Footer */}
      <div className="flex items-center justify-between mt-6 pt-4 border-t border-campfire-dark">
        <div className="flex space-x-6">
          <button className="flex items-center text-campfire-ash hover:text-campfire-amber">
            <FaThumbsUp className="mr-2" />
            <span>{likes}</span>
          </button>
          <button className="flex items-center text-campfire-ash hover:text-campfire-amber">
            {/* Safely access comments length */}
            <FaComment className="mr-2" />
            <span>{comments?.length || 0}</span>
          </button>
        </div>
        <button className="flex items-center text-campfire-ash hover:text-campfire-amber">
          <FaShare className="mr-2" />
          <span>Share</span>
        </button>
      </div>
    </div>
  );
}

export default ReviewCard;
