import { useState, useEffect } from "react";
import { api } from "@/services/api";
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, Legend } from "recharts";
import { Scale, Trophy, TrendingDown, AlertTriangle } from "lucide-react";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Link } from "react-router-dom";

const fmt = (n) => `Rp ${((n || 0) / 1000000).toFixed(1)}jt`;

export default function KomparasiSPPG() {
  const [sppgList, setSppgList] = useState([]);
  const [idA, setIdA] = useState("");
  const [idB, setIdB] = useState("");

  useEffect(() => { api.list("SPPG").then(setSppgList); }, []);

  const sppgA = sppgList.find((s) => s.id === idA);
  const sppgB = sppgList.find((s) => s.id === idB);

  const metrics = sppgA && sppgB ? [
    { label: "Total Dana", a: sppgA.total_dana || 0, b: sppgB.total_dana || 0, format: (v) => fmt(v) },
    { label: "Dana Dibelanjakan", a: sppgA.dana_dibelanjakan || 0, b: sppgB.dana_dibelanjakan || 0, format: (v) => fmt(v) },
    { label: "Sisa Dana", a: sppgA.sisa_dana || 0, b: sppgB.sisa_dana || 0, format: (v) => fmt(v) },
    { label: "Jumlah Omprengan", a: sppgA.jumlah_omprengan || 0, b: sppgB.jumlah_omprengan || 0, format: (v) => v.toLocaleString() },
  ] : [];

  const chartData = metrics.map((m) => ({ label: m.label, [sppgA?.nama]: m.a, [sppgB?.nama]: m.b }));

  const costPerA = sppgA?.jumlah_omprengan > 0 ? (sppgA.dana_dibelanjakan || 0) / sppgA.jumlah_omprengan : 0;
  const costPerB = sppgB?.jumlah_omprengan > 0 ? (sppgB.dana_dibelanjakan || 0) / sppgB.jumlah_omprengan : 0;
  const effA = sppgA?.dana_diterima > 0 ? ((sppgA.dana_dibelanjakan || 0) / sppgA.dana_diterima) * 100 : 0;
  const effB = sppgB?.dana_diterima > 0 ? ((sppgB.dana_dibelanjakan || 0) / sppgB.dana_diterima) * 100 : 0;

  return (
    <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-10">
      <div className="flex items-center gap-3 mb-8">
        <div className="w-10 h-10 bg-primary rounded-xl flex items-center justify-center">
          <Scale className="w-5 h-5 text-primary-foreground" />
        </div>
        <div>
          <h1 className="text-2xl font-black text-foreground">Perbandingan SPPG</h1>
          <p className="text-sm text-muted-foreground">Bandingkan efisiensi dan kinerja dua SPPG secara langsung</p>
        </div>
      </div>

      {/* SPPG Selectors */}
      <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 mb-8">
        {[{ id: idA, setId: setIdA, label: "SPPG A", color: "border-blue-300 bg-blue-50" },
          { id: idB, setId: setIdB, label: "SPPG B", color: "border-emerald-300 bg-emerald-50" }].map(({ id, setId, label, color }) => (
          <div key={label} className={`rounded-xl border-2 p-4 ${color}`}>
            <p className="text-xs font-bold text-muted-foreground mb-2">{label}</p>
            <Select value={id} onValueChange={setId}>
              <SelectTrigger className="bg-white">
                <SelectValue placeholder={`Pilih ${label}`} />
              </SelectTrigger>
              <SelectContent>
                {sppgList.map((s) => (
                  <SelectItem key={s.id} value={s.id}>{s.nama} — {s.provinsi}</SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
        ))}
      </div>

      {sppgA && sppgB ? (
        <>
          {/* Ranking / Winner */}
          <div className="grid grid-cols-1 sm:grid-cols-3 gap-4 mb-8">
            {[
              {
                label: "Biaya Per Porsi",
                valA: `Rp ${(costPerA / 1000).toFixed(1)}rb`,
                valB: `Rp ${(costPerB / 1000).toFixed(1)}rb`,
                winner: costPerA <= costPerB ? sppgA.nama : sppgB.nama,
                icon: TrendingDown,
                hint: "lebih hemat",
              },
              {
                label: "Efisiensi Dana",
                valA: `${effA.toFixed(1)}%`,
                valB: `${effB.toFixed(1)}%`,
                winner: effA <= effB ? sppgA.nama : sppgB.nama,
                icon: Trophy,
                hint: "penggunaan dana lebih tepat",
              },
              {
                label: "Jumlah Penerima",
                valA: (sppgA.jumlah_omprengan || 0).toLocaleString(),
                valB: (sppgB.jumlah_omprengan || 0).toLocaleString(),
                winner: (sppgA.jumlah_omprengan || 0) >= (sppgB.jumlah_omprengan || 0) ? sppgA.nama : sppgB.nama,
                icon: Trophy,
                hint: "lebih banyak penerima",
              },
            ].map((m) => (
              <div key={m.label} className="bg-card border border-border rounded-xl p-4">
                <m.icon className="w-4 h-4 text-primary mb-2" />
                <p className="text-xs font-semibold text-muted-foreground mb-3">{m.label}</p>
                <div className="grid grid-cols-2 gap-2 mb-3">
                  <div className="text-center bg-blue-50 rounded-lg p-2">
                    <p className="text-xs text-muted-foreground truncate">{sppgA.nama.split(" ")[0]}</p>
                    <p className="text-sm font-black text-blue-700">{m.valA}</p>
                  </div>
                  <div className="text-center bg-emerald-50 rounded-lg p-2">
                    <p className="text-xs text-muted-foreground truncate">{sppgB.nama.split(" ")[0]}</p>
                    <p className="text-sm font-black text-emerald-700">{m.valB}</p>
                  </div>
                </div>
                <div className="bg-amber-50 border border-amber-200 rounded-lg p-2 text-center">
                  <p className="text-xs text-amber-700"><span className="font-bold">{m.winner}</span> {m.hint}</p>
                </div>
              </div>
            ))}
          </div>

          {/* Bar Chart */}
          <div className="bg-card border border-border rounded-xl p-5 mb-8">
            <h3 className="font-bold text-foreground mb-4">Perbandingan Dana (dalam juta Rp)</h3>
            <ResponsiveContainer width="100%" height={280}>
              <BarChart data={[
                { metric: "Dana Total", [sppgA.nama]: (sppgA.total_dana || 0) / 1000000, [sppgB.nama]: (sppgB.total_dana || 0) / 1000000 },
                { metric: "Dibelanjakan", [sppgA.nama]: (sppgA.dana_dibelanjakan || 0) / 1000000, [sppgB.nama]: (sppgB.dana_dibelanjakan || 0) / 1000000 },
                { metric: "Sisa Dana", [sppgA.nama]: (sppgA.sisa_dana || 0) / 1000000, [sppgB.nama]: (sppgB.sisa_dana || 0) / 1000000 },
              ]} barSize={28}>
                <CartesianGrid strokeDasharray="3 3" vertical={false} />
                <XAxis dataKey="metric" fontSize={11} tickLine={false} axisLine={false} />
                <YAxis fontSize={11} tickLine={false} axisLine={false} />
                <Tooltip formatter={(v) => `Rp ${v.toFixed(1)}jt`} />
                <Legend />
                <Bar dataKey={sppgA.nama} fill="hsl(213 70% 35%)" radius={[4,4,0,0]} />
                <Bar dataKey={sppgB.nama} fill="hsl(152 55% 42%)" radius={[4,4,0,0]} />
              </BarChart>
            </ResponsiveContainer>
          </div>

          {/* Detail Table */}
          <div className="bg-card border border-border rounded-xl overflow-hidden">
            <div className="p-5 border-b border-border">
              <h3 className="font-bold text-foreground">Tabel Perbandingan Detail</h3>
            </div>
            <div className="overflow-x-auto">
              <table className="w-full text-sm">
                <thead className="bg-muted/50">
                  <tr>
                    <th className="text-left px-5 py-3 text-xs font-semibold text-muted-foreground">Indikator</th>
                    <th className="text-center px-5 py-3 text-xs font-semibold text-blue-600">{sppgA.nama}</th>
                    <th className="text-center px-5 py-3 text-xs font-semibold text-emerald-600">{sppgB.nama}</th>
                    <th className="text-center px-5 py-3 text-xs font-semibold text-muted-foreground">Lebih Baik</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-border">
                  {[
                    { label: "Provinsi", a: sppgA.provinsi, b: sppgB.provinsi, compare: false },
                    { label: "Status", a: sppgA.status, b: sppgB.status, compare: false },
                    { label: "Total Dana", a: fmt(sppgA.total_dana), b: fmt(sppgB.total_dana), raw: [sppgA.total_dana, sppgB.total_dana], higher: true },
                    { label: "Dana Dibelanjakan", a: fmt(sppgA.dana_dibelanjakan), b: fmt(sppgB.dana_dibelanjakan), compare: false },
                    { label: "Sisa Dana", a: fmt(sppgA.sisa_dana), b: fmt(sppgB.sisa_dana), raw: [sppgA.sisa_dana, sppgB.sisa_dana], higher: true },
                    { label: "Jml. Omprengan", a: (sppgA.jumlah_omprengan||0).toLocaleString(), b: (sppgB.jumlah_omprengan||0).toLocaleString(), raw: [sppgA.jumlah_omprengan, sppgB.jumlah_omprengan], higher: true },
                    { label: "Biaya/Omprengan", a: `Rp ${(costPerA/1000).toFixed(1)}rb`, b: `Rp ${(costPerB/1000).toFixed(1)}rb`, raw: [costPerA, costPerB], higher: false },
                  ].map((row) => {
                    let winner = null;
                    if (row.raw) {
                      winner = row.higher
                        ? (row.raw[0] >= row.raw[1] ? "A" : "B")
                        : (row.raw[0] <= row.raw[1] ? "A" : "B");
                    }
                    return (
                      <tr key={row.label} className="hover:bg-muted/20">
                        <td className="px-5 py-3 font-medium text-muted-foreground">{row.label}</td>
                        <td className={`px-5 py-3 text-center font-semibold ${winner === "A" ? "text-blue-600" : ""}`}>{row.a}</td>
                        <td className={`px-5 py-3 text-center font-semibold ${winner === "B" ? "text-emerald-600" : ""}`}>{row.b}</td>
                        <td className="px-5 py-3 text-center">
                          {winner && (
                            <span className={`px-2 py-0.5 rounded-full text-xs font-bold ${winner === "A" ? "bg-blue-100 text-blue-700" : "bg-emerald-100 text-emerald-700"}`}>
                              {winner === "A" ? sppgA.nama.split(" ")[0] : sppgB.nama.split(" ")[0]}
                            </span>
                          )}
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          </div>
        </>
      ) : (
        <div className="bg-card border border-border rounded-2xl p-16 text-center">
          <Scale className="w-12 h-12 text-muted-foreground mx-auto mb-4 opacity-30" />
          <p className="text-muted-foreground font-medium">Pilih dua SPPG untuk mulai membandingkan</p>
          <p className="text-sm text-muted-foreground mt-1">Data akan ditampilkan secara otomatis</p>
        </div>
      )}
    </div>
  );
}