"use client";

import { useState } from "react";
import { submitOrganizationRating } from "@/api/ratingApi";

export default function RatingSection() {
  const [rating, setRating] = useState(0);
  const [hover, setHover] = useState(0);
  const [review, setReview] = useState("");
  const [loading, setLoading] = useState(false);

  const handleSubmit = async () => {
    if (!rating) {
      alert("Please select a rating");
      return;
    }

    try {
      setLoading(true);

      await submitOrganizationRating({
        rating,
        review_text: review,
      });

      alert("Thanks for your feedback ❤️");
      setRating(0);
      setReview("");
    } catch (err: any) {
      if (err?.response?.status === 400) {
        alert("You already submitted a rating");
      } else {
        alert("Failed to submit rating");
      }
    } finally {
      setLoading(false);
    }
  };

  return (
    <section className="bg-gradient-to-r from-gray-900 to-black text-white py-14 px-6 mt-10">
      <div className="max-w-3xl mx-auto text-center">
        
        <h2 className="text-2xl sm:text-3xl font-bold mb-3">
          Rate Your Experience ⭐
        </h2>

        <p className="text-gray-400 mb-6">
          Tell us how your experience was with our platform
        </p>

        {/* ⭐ STAR RATING */}
        <div className="flex justify-center gap-2 mb-6">
          {[1, 2, 3, 4, 5].map((star) => (
            <span
              key={star}
              className={`text-3xl cursor-pointer transition ${
                (hover || rating) >= star
                  ? "text-yellow-400 scale-110"
                  : "text-gray-500"
              }`}
              onClick={() => setRating(star)}
              onMouseEnter={() => setHover(star)}
              onMouseLeave={() => setHover(0)}
            >
              ★
            </span>
          ))}
        </div>

        {/* REVIEW INPUT */}
        <textarea
          placeholder="Write your review..."
          value={review}
          onChange={(e) => setReview(e.target.value)}
          className="w-full bg-gray-800 border border-gray-700 rounded-lg p-3 text-sm focus:outline-none focus:ring-2 focus:ring-yellow-400"
          rows={4}
        />

        {/* SUBMIT BUTTON */}
        <button
          onClick={handleSubmit}
          disabled={loading}
          className="mt-6 bg-yellow-400 text-black font-semibold px-6 py-2 rounded-lg hover:bg-yellow-500 transition disabled:opacity-50"
        >
          {loading ? "Submitting..." : "Submit Rating"}
        </button>
      </div>
    </section>
  );
}