import { useEffect, useState } from "react";
import {
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
  LineChart,
  Line,
} from "recharts";
import {
  AlertTriangle,
  Building2,
  Wallet,
  Users,
  CheckCircle2,
  Activity,
  Eye,
  ShieldCheck,
  TrendingUp,
  Clock,
  MapPin,
} from "lucide-react";
import { Link } from "react-router-dom";

const LIST_SPPG_API = "http://localhost/backend/api/sppg/list.php";

const aktivitasData = [
  { tanggal: "25 Apr", laporan: 12, validasi: 10 },
  { tanggal: "26 Apr", laporan: 15, validasi: 14 },
  { tanggal: "27 Apr", laporan: 9, validasi: 8 },
  { tanggal: "28 Apr", laporan: 18, validasi: 16 },
  { tanggal: "29 Apr", laporan: 22, validasi: 19 },
  { tanggal: "30 Apr", laporan: 17, validasi: 15 },
];

const trenDanaData = [
  { bulan: "Jan", dana: 32 },
  { bulan: "Feb", dana: 38 },
  { bulan: "Mar", dana: 42 },
  { bulan: "Apr", dana: 47 },
  { bulan: "Mei", dana: 50 },
];

const timelineItems = [
  {
    sppg: "SPPG Padang Utara",
    action: "Laporan menu omprengan harian dikirim",
    time: "10:23",
    date: "Hari ini",
    type: "info",
  },
  {
    sppg: "SPPG Bukittinggi",
    action: "Laporan distribusi disetujui validator",
    time: "09:45",
    date: "Hari ini",
    type: "success",
  },
  {
    sppg: "SPPG Medan Kota",
    action: "Bukti foto makanan jadi berhasil diunggah",
    time: "08:12",
    date: "Hari ini",
    type: "warning",
  },
  {
    sppg: "SPPG Padang Utara",
    action: "Dana operasional bulan ini tercatat",
    time: "07:30",
    date: "Kemarin",
    type: "success",
  },
];

const formatRp = (n) =>
  `Rp ${(Number(n) || 0).toLocaleString("id-ID")}`;

const getStatusStyle = (status) => {
  if (status === "Aktif") return "bg-emerald-100 text-emerald-700";
  if (status === "Pemantauan") return "bg-yellow-100 text-yellow-700";
  return "bg-red-100 text-red-700";
};

const getTimelineDot = (type) => {
  if (type === "success") return "bg-emerald-500";
  if (type === "warning") return "bg-yellow-500";
  return "bg-blue-500";
};

function StatBox({ title, value, desc, icon: Icon, tone = "blue" }) {
  const toneClass = {
    blue: "bg-blue-50 text-blue-700",
    emerald: "bg-emerald-50 text-emerald-700",
    yellow: "bg-yellow-50 text-yellow-700",
    purple: "bg-purple-50 text-purple-700",
  };

  return (
    <div className="rounded-3xl border border-border bg-card p-5 shadow-sm">
      <div
        className={`mb-4 flex h-12 w-12 items-center justify-center rounded-2xl ${
          toneClass[tone] || toneClass.blue
        }`}
      >
        <Icon className="h-6 w-6" />
      </div>

      <p className="text-sm text-muted-foreground">{title}</p>
      <p className="mt-1 text-3xl font-black text-foreground">{value}</p>
      {desc && <p className="mt-1 text-xs text-muted-foreground">{desc}</p>}
    </div>
  );
}

export default function DashboardNasional() {
  const [sppgList, setSppgList] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");

  const loadData = async () => {
    try {
      setLoading(true);
      setError("");

      const res = await fetch(LIST_SPPG_API);

      if (!res.ok) {
        throw new Error(`HTTP Error ${res.status}`);
      }

      const result = await res.json();

      if (result.success && Array.isArray(result.data)) {
        setSppgList(result.data);
      } else {
        setSppgList([]);
        setError(result.message || "Data SPPG tidak sesuai.");
      }
    } catch (err) {
      console.error("Gagal mengambil data dashboard pemerintah:", err);
      setSppgList([]);
      setError("Gagal mengambil data dashboard pemerintah dari server.");
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadData();
  }, []);

  const totalSPPG = sppgList.length;
  const sppgAktif = sppgList.filter((s) => s.status === "Aktif").length;
  const totalDana = sppgList.reduce(
    (acc, s) => acc + (Number(s.total_dana) || 0),
    0
  );
  const totalSiswa = sppgList.reduce(
    (acc, s) => acc + (Number(s.jumlah_siswa) || 0),
    0
  );

  const sppgPemantauan = sppgList.filter(
    (s) => s.status === "Pemantauan"
  ).length;

  const skorTransparansi =
    totalSPPG > 0 ? Math.round((sppgAktif / totalSPPG) * 100) : 0;

  const topSppg = [...sppgList]
    .sort((a, b) => (Number(b.total_dana) || 0) - (Number(a.total_dana) || 0))
    .slice(0, 5);

  return (
    <div className="mx-auto max-w-7xl space-y-8 p-4 sm:p-6 lg:p-8">
      <div className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
        <div>
          <div className="mb-3 flex h-12 w-12 items-center justify-center rounded-2xl bg-blue-100 text-blue-700">
            <ShieldCheck className="h-6 w-6" />
          </div>

          <h1 className="text-2xl font-black text-foreground">
            Dashboard Nasional
          </h1>

          <p className="mt-1 max-w-2xl text-sm text-muted-foreground">
            Monitoring dan pengawasan program MBG secara nasional. Pemerintah
            dapat melihat data, laporan, distribusi, dan status SPPG tanpa
            mengubah data operasional.
          </p>
        </div>

        <button
          type="button"
          onClick={loadData}
          className="w-fit rounded-xl border border-border bg-white px-4 py-2 text-sm font-bold text-slate-700 shadow-sm transition hover:bg-slate-50"
        >
          Refresh Data
        </button>
      </div>

      {error && (
        <div className="rounded-2xl border border-red-200 bg-red-50 px-4 py-3 text-sm font-semibold text-red-600">
          {error}
        </div>
      )}

      {sppgPemantauan > 0 && (
        <div className="rounded-3xl border border-yellow-200 bg-yellow-50 p-5">
          <div className="flex items-start gap-3">
            <div className="flex h-11 w-11 flex-shrink-0 items-center justify-center rounded-2xl bg-yellow-100 text-yellow-700">
              <AlertTriangle className="h-5 w-5" />
            </div>

            <div>
              <h2 className="font-black text-yellow-900">
                Perhatian Pemerintah
              </h2>
              <p className="mt-1 text-sm text-yellow-800">
                Terdapat {sppgPemantauan} SPPG dalam status pemantauan. Data
                tersebut perlu diperiksa melalui aktivitas SPPG atau laporan
                terkait.
              </p>
            </div>
          </div>
        </div>
      )}

      <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
        <StatBox
          title="Total SPPG"
          value={totalSPPG.toLocaleString("id-ID")}
          desc="SPPG terdaftar dalam sistem"
          icon={Building2}
          tone="blue"
        />

        <StatBox
          title="SPPG Aktif"
          value={sppgAktif.toLocaleString("id-ID")}
          desc="SPPG berstatus aktif"
          icon={CheckCircle2}
          tone="emerald"
        />

        <StatBox
          title="Total Dana Nasional"
          value={formatRp(totalDana)}
          desc="Akumulasi dana tercatat"
          icon={Wallet}
          tone="yellow"
        />

        <StatBox
          title="Total Siswa"
          value={totalSiswa.toLocaleString("id-ID")}
          desc="Penerima manfaat terdata"
          icon={Users}
          tone="purple"
        />
      </div>

      <div className="grid gap-6 lg:grid-cols-[1.4fr_0.8fr]">
        <div className="rounded-3xl border border-border bg-card p-5 shadow-sm">
          <div className="mb-4 flex items-center justify-between">
            <div>
              <h3 className="font-bold text-foreground">
                Aktivitas Laporan Harian
              </h3>
              <p className="text-sm text-muted-foreground">
                Perbandingan laporan masuk dan data tervalidasi.
              </p>
            </div>

            <Activity className="h-5 w-5 text-blue-700" />
          </div>

          <ResponsiveContainer width="100%" height={280}>
            <BarChart data={aktivitasData} barSize={22}>
              <CartesianGrid
                strokeDasharray="3 3"
                vertical={false}
                stroke="hsl(210 25% 88%)"
              />
              <XAxis
                dataKey="tanggal"
                fontSize={11}
                tickLine={false}
                axisLine={false}
              />
              <YAxis fontSize={11} tickLine={false} axisLine={false} />
              <Tooltip />
              <Bar
                dataKey="laporan"
                name="Laporan Masuk"
                fill="hsl(213 70% 35%)"
                radius={[6, 6, 0, 0]}
              />
              <Bar
                dataKey="validasi"
                name="Tervalidasi"
                fill="hsl(152 55% 42%)"
                radius={[6, 6, 0, 0]}
              />
            </BarChart>
          </ResponsiveContainer>
        </div>

        <div className="rounded-3xl border border-border bg-card p-5 shadow-sm">
          <div className="mb-4">
            <h3 className="font-bold text-foreground">Skor Pengawasan</h3>
            <p className="text-sm text-muted-foreground">
              Indikator sederhana berdasarkan status SPPG aktif.
            </p>
          </div>

          <div className="flex h-48 items-center justify-center">
            <div className="relative flex h-40 w-40 items-center justify-center rounded-full border-[14px] border-blue-100">
              <div className="absolute inset-0 rounded-full border-[14px] border-transparent border-t-blue-700 border-r-blue-700" />
              <div className="text-center">
                <p className="text-4xl font-black text-blue-700">
                  {skorTransparansi}
                </p>
                <p className="text-xs font-bold text-muted-foreground">
                  dari 100
                </p>
              </div>
            </div>
          </div>

          <div className="rounded-2xl bg-blue-50 p-4 text-sm text-blue-800">
            Semakin banyak SPPG aktif, semakin tinggi skor pengawasan awal.
            Pemeriksaan lanjutan tetap dilakukan melalui laporan dan validasi.
          </div>
        </div>
      </div>

      <div className="grid gap-6 lg:grid-cols-[0.9fr_1.1fr]">
        <div className="rounded-3xl border border-border bg-card p-5 shadow-sm">
          <div className="mb-4 flex items-center justify-between">
            <div>
              <h3 className="font-bold text-foreground">Tren Dana Nasional</h3>
              <p className="text-sm text-muted-foreground">
                Gambaran dana tercatat per bulan.
              </p>
            </div>

            <TrendingUp className="h-5 w-5 text-blue-700" />
          </div>

          <ResponsiveContainer width="100%" height={260}>
            <LineChart data={trenDanaData}>
              <CartesianGrid
                strokeDasharray="3 3"
                vertical={false}
                stroke="hsl(210 25% 88%)"
              />
              <XAxis
                dataKey="bulan"
                fontSize={12}
                tickLine={false}
                axisLine={false}
              />
              <YAxis fontSize={12} tickLine={false} axisLine={false} />
              <Tooltip />
              <Line
                type="monotone"
                dataKey="dana"
                name="Dana Nasional Miliar"
                stroke="hsl(213, 70%, 35%)"
                strokeWidth={2.5}
                dot={{ r: 4 }}
              />
            </LineChart>
          </ResponsiveContainer>
        </div>

        <div className="rounded-3xl border border-border bg-card shadow-sm">
          <div className="border-b border-border p-5">
            <h3 className="font-bold text-foreground">
              SPPG dengan Dana Tertinggi
            </h3>
            <p className="text-sm text-muted-foreground">
              Pemerintah dapat membuka detail untuk melakukan pemantauan.
            </p>
          </div>

          {loading ? (
            <div className="flex items-center justify-center py-16">
              <div className="h-8 w-8 animate-spin rounded-full border-4 border-blue-100 border-t-blue-700" />
            </div>
          ) : topSppg.length === 0 ? (
            <div className="py-16 text-center text-sm text-muted-foreground">
              Belum ada data SPPG.
            </div>
          ) : (
            <div className="divide-y divide-border">
              {topSppg.map((item) => (
                <div
                  key={item.id}
                  className="flex flex-col gap-3 p-5 sm:flex-row sm:items-center sm:justify-between"
                >
                  <div>
                    <p className="font-black text-foreground">
                      {item.nama || "-"}
                    </p>

                    <div className="mt-1 flex items-center gap-1 text-xs text-muted-foreground">
                      <MapPin className="h-3.5 w-3.5" />
                      {item.kabupaten || "-"}, {item.provinsi || "-"}
                    </div>

                    <p className="mt-1 text-sm font-bold text-primary">
                      {formatRp(item.total_dana)}
                    </p>
                  </div>

                  <div className="flex items-center gap-2">
                    <span
                      className={`rounded-full px-3 py-1 text-xs font-bold ${getStatusStyle(
                        item.status
                      )}`}
                    >
                      {item.status || "-"}
                    </span>

                    <Link
                      to={`/detail-sppg/${item.id}`}
                      className="inline-flex items-center gap-1 rounded-xl border border-blue-100 bg-white px-3 py-2 text-xs font-bold text-blue-700 shadow-sm transition hover:bg-blue-700 hover:text-white"
                    >
                      <Eye className="h-4 w-4" />
                      Detail
                    </Link>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>

      <div className="rounded-3xl border border-border bg-card shadow-sm">
        <div className="border-b border-border p-5">
          <h3 className="font-bold text-foreground">
            Timeline Aktivitas SPPG
          </h3>
          <p className="text-sm text-muted-foreground">
            Ringkasan aktivitas terbaru yang perlu dipantau pemerintah.
          </p>
        </div>

        <div className="divide-y divide-border">
          {timelineItems.map((item, index) => (
            <div key={index} className="flex items-start gap-4 px-5 py-4">
              <div
                className={`mt-2 h-3 w-3 flex-shrink-0 rounded-full ${getTimelineDot(
                  item.type
                )}`}
              />

              <div className="min-w-0 flex-1">
                <p className="text-sm font-bold text-foreground">
                  {item.sppg}
                </p>
                <p className="mt-0.5 text-sm text-muted-foreground">
                  {item.action}
                </p>
              </div>

              <div className="flex-shrink-0 text-right">
                <p className="flex items-center gap-1 text-xs font-bold text-foreground">
                  <Clock className="h-3.5 w-3.5" />
                  {item.time}
                </p>
                <p className="mt-0.5 text-xs text-muted-foreground">
                  {item.date}
                </p>
              </div>
            </div>
          ))}
        </div>
      </div>

      <div className="rounded-3xl border border-blue-100 bg-blue-50 p-5 text-sm text-blue-800">
        <p className="font-black">Catatan hak akses pemerintah</p>
        <p className="mt-1 leading-relaxed">
          Akun pemerintah hanya digunakan untuk pemantauan nasional. Pemerintah
          dapat melihat dashboard, detail SPPG, aktivitas, dan laporan dana,
          tetapi tidak dapat menambah, mengedit, atau menghapus data SPPG.
        </p>
      </div>
    </div>
  );
}