'use client';

import { FaStar } from "react-icons/fa";
import Heading from '../atoms/Heading';
import { BsFillPersonFill } from "react-icons/bs";

const UniversityReviews = ({ university }) => {
  // Parse review data from university object
  const getReviews = () => {
    try {
      // Check if review_detail exists and is not empty
      if (!university?.review_detail) return [];
      
      // Handle both stringified JSON and direct object
      const reviewData = typeof university.review_detail === 'string' 
        ? JSON.parse(university.review_detail) 
        : university.review_detail;
      
      // Convert to array if it's a single review object
      return Array.isArray(reviewData) ? reviewData : [reviewData];
    } catch (error) {
      console.error('Error parsing reviews:', error);
      return [];
    }
  };

  const reviews = getReviews();

  // Calculate average rating - convert string ratings to numbers
  const averageRating = reviews.length > 0 
    ? (reviews.reduce((sum, review) => sum + (parseInt(review.rating) || 0), 0) / reviews.length) 
    : 0;

  const gradientStyle = {
    background: 'linear-gradient(135deg, #0B6F78 0%, #0a306b 100%)',
  };

  return (
    <div className="rounded-2xl shadow-2xl overflow-hidden">
      {/* Header with Gradient */}
      <div style={gradientStyle} className="p-8 text-white">
        <div className="flex items-center gap-3 mb-2">
          <div className="bg-white bg-opacity-20 p-2 rounded-lg">
            <FaStar className="text-xl" />
          </div>
          <Heading level={3} className="text-2xl font-bold">Student Reviews</Heading>
        </div>
        <p className="text-blue-100">Hear what students say about {university.name}</p>
      </div>

      {/* Content */}
      <div className="bg-white p-8">
        {/* Overall Rating Card */}
        <div className="bg-gradient-to-r from-blue-50 to-cyan-50 rounded-xl p-6 mb-8 border border-blue-100">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-6">
              <div className="text-5xl font-bold text-[#0a306b]">{averageRating.toFixed(1)}</div>
              <div className="flex flex-col">
                <div className="flex gap-1 mb-2">
                  {[...Array(5)].map((_, i) => (
                    <FaStar 
                      key={i} 
                      className={`text-2xl ${i < Math.round(averageRating) ? "text-yellow-400" : "text-gray-300"}`} 
                    />
                  ))}
                </div>
                <span className="text-lg text-gray-700 font-medium">
                  Based on {reviews.length} review{reviews.length !== 1 ? 's' : ''}
                </span>
              </div>
            </div>
            <div className="bg-[#0B6F78] text-white px-4 py-2 rounded-lg font-semibold">
              {averageRating.toFixed(1)}/5
            </div>
          </div>
        </div>

        {/* Reviews List */}
        {reviews.length > 0 ? (
          <div className="space-y-6">
            {reviews.map((review, idx) => (
              <div key={idx} className="bg-gray-50 rounded-xl p-6 hover:shadow-lg transition-shadow duration-300 border border-gray-100">
                <div className="flex items-start gap-4">
                  <div className="bg-[#0B6F78] p-3 rounded-full">
                    <BsFillPersonFill className="text-white text-xl" />
                  </div>
                  <div className="flex-1">
                    <div className="flex items-center justify-between mb-3">
                      <div>
                        <p className="font-bold text-gray-800 text-lg">
                          {review.reviewerName || review.authorName || 'Anonymous Student'}
                        </p>
                        <div className="flex items-center gap-1 mt-1">
                          {[...Array(5)].map((_, i) => (
                            <FaStar 
                              key={i} 
                              className={`text-sm ${i < (parseInt(review.rating) || 0) ? "text-yellow-400" : "text-gray-300"}`} 
                            />
                          ))}
                          <span className="text-sm text-gray-600 ml-2">
                            {parseInt(review.rating) || 0}.0/5.0
                          </span>
                        </div>
                      </div>
                      {review.reviewDate && (
                        <span className="text-sm text-gray-500">
                          {new Date(review.reviewDate).toLocaleDateString()}
                        </span>
                      )}
                    </div>
                    
                    <p className="text-gray-700 leading-relaxed">{review.reviewDescription}</p>
                    
                    {review.publisherName && (
                      <div className="mt-3 pt-3 border-t border-gray-200">
                        <span className="text-xs text-gray-500 bg-blue-50 px-2 py-1 rounded">
                          Published by: {review.publisherName}
                        </span>
                      </div>
                    )}
                  </div>
                </div>
              </div>
            ))}
          </div>
        ) : (
          <div className="text-center py-12 bg-gradient-to-br from-blue-50 to-cyan-50 rounded-2xl">
            <div className="bg-white w-16 h-16 rounded-full flex items-center justify-center mx-auto mb-4 shadow-lg">
              <FaStar className="text-2xl text-yellow-400" />
            </div>
            <p className="text-lg text-gray-600 font-semibold mb-2">No reviews yet</p>
            <p className="text-gray-500">Be the first to share your experience!</p>
            <button className="mt-4 bg-[#0a306b] text-white px-6 py-2 rounded-lg font-semibold hover:bg-[#0B6F78] transition duration-300">
              Write a Review
            </button>
          </div>
        )}
      </div>
    </div>
  );
};

export default UniversityReviews;