import { useState, useEffect } from "react";
import { Trophy, Star, ArrowRight, MessageSquare, ThumbsUp } from "lucide-react";
import { Link } from "react-router-dom";
import { api } from "@/services/api";

export default function SPPGHighlight() {
  const [sppgList, setSppgList] = useState([]);
  const [ratings, setRatings] = useState([]);
  const [pengaduan, setPengaduan] = useState([]);

  useEffect(() => {
    Promise.all([
      api.list("SPPG"),
      api.list("RatingFeedback"),
      api.list("Pengaduan"),
    ]).then(([s, r, p]) => {
      setSppgList(s);
      setRatings(r);
      setPengaduan(p);
    });
  }, []);

  const scored = sppgList
    .filter((s) => s.status === "Aktif")
    .map((s) => {
      // Average rating (0-5 → weight 40%)
      const sppgRatings = ratings.filter((r) => r.sppg_id === s.id);
      const avgRating = sppgRatings.length > 0
        ? sppgRatings.reduce((a, r) => a + (r.rating || 0), 0) / sppgRatings.length
        : 0;

      // Pengaduan penalty: fewer = better (weight 40%)
      const sppgPengaduan = pengaduan.filter((p) => p.sppg_nama === s.nama);
      const resolved = sppgPengaduan.filter((p) => p.status === "Selesai").length;
      const total = sppgPengaduan.length;
      const pengaduanScore = total === 0 ? 5 : (resolved / total) * 5;

      // Validator score: dana efficiency as proxy (weight 20%)
      const effScore = s.dana_diterima > 0
        ? Math.min(((s.dana_dibelanjakan || 0) / s.dana_diterima) * 5, 5)
        : 0;

      const finalScore = (avgRating * 0.4) + (pengaduanScore * 0.4) + (effScore * 0.2);

      return {
        ...s,
        avgRating,
        pengaduanTotal: total,
        pengaduanResolved: resolved,
        finalScore,
        ratingCount: sppgRatings.length,
      };
    })
    .sort((a, b) => b.finalScore - a.finalScore)
    .slice(0, 3);

  if (!scored.length) return null;

  const medals = ["🥇", "🥈", "🥉"];
  const medalColors = [
    "bg-amber-400 text-white",
    "bg-slate-300 text-slate-700",
    "bg-amber-700/30 text-amber-900",
  ];

  return (
    <section className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 pb-16">
      <div className="bg-gradient-to-br from-amber-50 to-orange-50 border border-amber-200 rounded-2xl p-6">
        <div className="flex items-center gap-3 mb-5">
          <div className="w-10 h-10 bg-amber-400 rounded-xl flex items-center justify-center">
            <Trophy className="w-5 h-5 text-white" />
          </div>
          <div>
            <h3 className="font-bold text-amber-900 text-lg">SPPG Terbaik</h3>
            <p className="text-xs text-amber-600">
              Berdasarkan penilaian masyarakat, penyelesaian pengaduan, dan efisiensi dana
            </p>
          </div>
        </div>

        <div className="space-y-3">
          {scored.map((s, i) => (
            <Link
              key={s.id}
              to={`/detail-sppg/${s.id}`}
              className="flex items-center gap-3 bg-white/80 hover:bg-white rounded-xl p-4 transition-colors group shadow-sm"
            >
              <div className={`w-9 h-9 rounded-lg flex items-center justify-center text-sm font-black flex-shrink-0 ${medalColors[i]}`}>
                {medals[i]}
              </div>
              <div className="flex-1 min-w-0">
                <p className="text-sm font-bold text-foreground truncate">{s.nama}</p>
                <p className="text-xs text-muted-foreground">{s.provinsi}</p>
                <div className="flex items-center gap-3 mt-1">
                  <span className="flex items-center gap-1 text-xs text-amber-600">
                    <Star className="w-3 h-3 fill-amber-400 text-amber-400" />
                    {s.avgRating.toFixed(1)} ({s.ratingCount} ulasan)
                  </span>
                  <span className="flex items-center gap-1 text-xs text-blue-600">
                    <MessageSquare className="w-3 h-3" />
                    {s.pengaduanResolved}/{s.pengaduanTotal} pengaduan selesai
                  </span>
                </div>
              </div>
              <div className="flex flex-col items-end gap-1 flex-shrink-0">
                <div className="flex items-center gap-1">
                  <ThumbsUp className="w-3.5 h-3.5 text-emerald-600" />
                  <span className="text-sm font-black text-emerald-700">{s.finalScore.toFixed(1)}</span>
                  <span className="text-xs text-muted-foreground">/5</span>
                </div>
                <ArrowRight className="w-3.5 h-3.5 text-muted-foreground opacity-0 group-hover:opacity-100 transition-opacity" />
              </div>
            </Link>
          ))}
        </div>
      </div>
    </section>
  );
}