import { useState, useEffect } from "react";
import { Star, Send, MessageSquare } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import { api } from "@/services/api";
import { toast } from "sonner";

export default function RatingFeedback({ sppgId, sppgNama }) {
  const [rating, setRating] = useState(0);
  const [hovered, setHovered] = useState(0);
  const [komentar, setKomentar] = useState("");
  const [submitting, setSubmitting] = useState(false);
  const [feedbackList, setFeedbackList] = useState([]);
  const [avgRating, setAvgRating] = useState(0);

  useEffect(() => {
    api.filter("RatingFeedback", { sppg_id: sppgId }).then((data) => {
      setFeedbackList(data);
      if (data.length) {
        setAvgRating(data.reduce((acc, f) => acc + (f.rating || 0), 0) / data.length);
      }
    });
  }, [sppgId]);

  const handleSubmit = async () => {
    if (!rating) { toast.error("Pilih rating terlebih dahulu"); return; }
    setSubmitting(true);
    await api.create("RatingFeedback", { sppg_id: sppgId, sppg_nama: sppgNama, rating, komentar });
    toast.success("Terima kasih atas feedback Anda!");
    setRating(0);
    setKomentar("");
    const updated = await api.filter("RatingFeedback", { sppg_id: sppgId });
    setFeedbackList(updated);
    setAvgRating(updated.reduce((acc, f) => acc + (f.rating || 0), 0) / updated.length);
    setSubmitting(false);
  };

  return (
    <div className="bg-card rounded-xl border border-border p-5 sm:p-6">
      <div className="flex items-center justify-between mb-4">
        <div className="flex items-center gap-2">
          <MessageSquare className="w-5 h-5 text-primary" />
          <h3 className="font-bold text-foreground">Rating &amp; Feedback Masyarakat</h3>
        </div>
        {avgRating > 0 && (
          <div className="flex items-center gap-1.5 bg-amber-50 border border-amber-200 rounded-full px-3 py-1">
            <Star className="w-3.5 h-3.5 fill-amber-400 text-amber-400" />
            <span className="text-sm font-bold text-amber-700">{avgRating.toFixed(1)}</span>
            <span className="text-xs text-amber-600">({feedbackList.length} ulasan)</span>
          </div>
        )}
      </div>

      {/* Rating Input */}
      <div className="bg-muted/30 rounded-xl p-4 mb-5">
        <p className="text-sm font-medium text-foreground mb-3">Beri rating untuk layanan MBG di SPPG ini:</p>
        <div className="flex gap-1.5 mb-3">
          {[1, 2, 3, 4, 5].map((s) => (
            <button
              key={s}
              onMouseEnter={() => setHovered(s)}
              onMouseLeave={() => setHovered(0)}
              onClick={() => setRating(s)}
              className="transition-transform hover:scale-110"
            >
              <Star className={`w-8 h-8 transition-colors ${s <= (hovered || rating) ? "fill-amber-400 text-amber-400" : "text-muted-foreground"}`} />
            </button>
          ))}
          {rating > 0 && (
            <span className="ml-2 text-sm font-semibold text-amber-600 self-center">
              {["", "Sangat Buruk", "Buruk", "Cukup", "Baik", "Sangat Baik"][rating]}
            </span>
          )}
        </div>
        <Textarea
          rows={2}
          placeholder="Tambahkan komentar (opsional)..."
          value={komentar}
          onChange={(e) => setKomentar(e.target.value)}
          className="bg-white text-sm"
        />
        <Button size="sm" className="mt-3 rounded-full" onClick={handleSubmit} disabled={submitting || !rating}>
          <Send className="w-3.5 h-3.5 mr-1.5" />
          {submitting ? "Mengirim..." : "Kirim Feedback"}
        </Button>
      </div>

      {/* Recent Feedback */}
      {feedbackList.length > 0 && (
        <div className="space-y-2">
          <p className="text-xs font-semibold text-muted-foreground uppercase tracking-wider">Ulasan Terbaru</p>
          {feedbackList.slice(0, 4).map((f) => (
            <div key={f.id} className="flex items-start gap-3 bg-muted/20 rounded-lg p-3">
              <div className="w-7 h-7 bg-primary/10 rounded-full flex items-center justify-center flex-shrink-0 text-xs font-bold text-primary">
                {f.created_by?.[0]?.toUpperCase() || "A"}
              </div>
              <div className="flex-1 min-w-0">
                <div className="flex items-center gap-2 mb-0.5">
                  <div className="flex">
                    {[1,2,3,4,5].map((s) => (
                      <Star key={s} className={`w-3 h-3 ${s <= f.rating ? "fill-amber-400 text-amber-400" : "text-muted-foreground"}`} />
                    ))}
                  </div>
                  <span className="text-xs text-muted-foreground">{new Date(f.created_date).toLocaleDateString("id-ID")}</span>
                </div>
                {f.komentar && <p className="text-xs text-foreground leading-relaxed">{f.komentar}</p>}
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}