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

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

const grafik = [
  { bulan: "Jan", aktif: 120, laporan: 480 },
  { bulan: "Feb", aktif: 135, laporan: 540 },
  { bulan: "Mar", aktif: 142, laporan: 568 },
  { bulan: "Apr", aktif: 158, laporan: 632 },
  { bulan: "Mei", aktif: 160, laporan: 640 },
];

const distribusiData = [
  { wilayah: "Padang", porsi: 1200, validasi: 1080 },
  { wilayah: "Bukittinggi", porsi: 850, validasi: 800 },
  { wilayah: "Medan", porsi: 970, validasi: 910 },
  { wilayah: "Mandailing", porsi: 760, validasi: 690 },
];

const aktivitasTerbaru = [
  {
    sppg: "SPPG Padang Utara",
    kegiatan: "Mengirim laporan menu omprengan harian",
    waktu: "Hari ini, 08.20",
    status: "Menunggu Validasi",
    tipe: "warning",
  },
  {
    sppg: "SPPG Bukittinggi",
    kegiatan: "Laporan distribusi disetujui validator",
    waktu: "Hari ini, 09.15",
    status: "Tervalidasi",
    tipe: "success",
  },
  {
    sppg: "SPPG Medan Kota",
    kegiatan: "Mengunggah bukti foto makanan jadi",
    waktu: "Kemarin, 14.40",
    status: "Diproses",
    tipe: "info",
  },
];

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";
};

export default function AktivitasSPPG() {
  const [sppgList, setSppgList] = useState([]);
  const [filterSppg, setFilterSppg] = useState("all");
  const [filterStatus, setFilterStatus] = useState("all");
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");

  const loadSPPG = 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 SPPG:", err);
      setSppgList([]);
      setError("Gagal mengambil data SPPG dari server.");
    } finally {
      setLoading(false);
    }
  };

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

  const filteredSPPG = sppgList.filter((item) => {
    const matchSppg =
      filterSppg === "all" || String(item.id) === String(filterSppg);

    const matchStatus =
      filterStatus === "all" || item.status === filterStatus;

    return matchSppg && matchStatus;
  });

  const totalSPPG = sppgList.length;

  const totalAktif = sppgList.filter((item) => item.status === "Aktif").length;

  const totalDana = sppgList.reduce(
    (total, item) => total + (Number(item.total_dana) || 0),
    0
  );

  const totalSiswa = sppgList.reduce(
    (total, item) => total + (Number(item.jumlah_siswa) || 0),
    0
  );

  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">
            <Activity className="h-6 w-6" />
          </div>

          <h1 className="text-2xl font-black text-foreground">
            Aktivitas SPPG
          </h1>

          <p className="mt-1 max-w-2xl text-sm text-muted-foreground">
            Pantau aktivitas, laporan, distribusi, dan penggunaan dana SPPG
            secara nasional. Pemerintah hanya dapat melihat dan memantau data,
            bukan mengubah data.
          </p>
        </div>

        <button
          onClick={loadSPPG}
          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>
      )}

      <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
        <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 bg-blue-50 text-blue-700">
            <Building2 className="h-6 w-6" />
          </div>
          <p className="text-sm text-muted-foreground">Total SPPG</p>
          <p className="mt-1 text-3xl font-black text-foreground">
            {totalSPPG.toLocaleString("id-ID")}
          </p>
        </div>

        <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 bg-emerald-50 text-emerald-700">
            <CheckCircle2 className="h-6 w-6" />
          </div>
          <p className="text-sm text-muted-foreground">SPPG Aktif</p>
          <p className="mt-1 text-3xl font-black text-foreground">
            {totalAktif.toLocaleString("id-ID")}
          </p>
        </div>

        <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 bg-yellow-50 text-yellow-700">
            <Wallet className="h-6 w-6" />
          </div>
          <p className="text-sm text-muted-foreground">Total Dana</p>
          <p className="mt-1 text-2xl font-black text-foreground">
            {formatRp(totalDana)}
          </p>
        </div>

        <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 bg-purple-50 text-purple-700">
            <Users className="h-6 w-6" />
          </div>
          <p className="text-sm text-muted-foreground">Total Siswa</p>
          <p className="mt-1 text-3xl font-black text-foreground">
            {totalSiswa.toLocaleString("id-ID")}
          </p>
        </div>
      </div>

      <div className="rounded-3xl border border-border bg-card p-5 shadow-sm">
        <div className="mb-4 flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
          <div>
            <h3 className="font-bold text-foreground">Filter Pemantauan</h3>
            <p className="text-sm text-muted-foreground">
              Pilih SPPG atau status tertentu untuk memantau data.
            </p>
          </div>

          <div className="flex flex-col gap-3 sm:flex-row">
            <div className="flex items-center gap-2">
              <Filter className="h-4 w-4 text-muted-foreground" />

              <select
                value={filterSppg}
                onChange={(e) => setFilterSppg(e.target.value)}
                className="h-10 rounded-xl border border-input bg-background px-3 text-sm"
              >
                <option value="all">Semua SPPG</option>

                {sppgList.map((s) => (
                  <option key={s.id} value={s.id}>
                    {s.nama}
                  </option>
                ))}
              </select>
            </div>

            <select
              value={filterStatus}
              onChange={(e) => setFilterStatus(e.target.value)}
              className="h-10 rounded-xl border border-input bg-background px-3 text-sm"
            >
              <option value="all">Semua Status</option>
              <option value="Aktif">Aktif</option>
              <option value="Pemantauan">Pemantauan</option>
              <option value="Tidak Aktif">Tidak Aktif</option>
            </select>
          </div>
        </div>
      </div>

      <div className="grid gap-6 lg:grid-cols-2">
        <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">
                Grafik Aktivitas Bulanan
              </h3>
              <p className="text-sm text-muted-foreground">
                Tren SPPG aktif dan laporan masuk.
              </p>
            </div>

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

          <ResponsiveContainer width="100%" height={280}>
            <LineChart data={grafik}>
              <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="aktif"
                name="SPPG Aktif"
                stroke="hsl(213, 70%, 35%)"
                strokeWidth={2.5}
                dot={{ r: 4 }}
              />
              <Line
                type="monotone"
                dataKey="laporan"
                name="Laporan Masuk"
                stroke="hsl(152, 55%, 42%)"
                strokeWidth={2.5}
                dot={{ r: 4 }}
              />
            </LineChart>
          </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">
              Distribusi dan Validasi Wilayah
            </h3>
            <p className="text-sm text-muted-foreground">
              Perbandingan porsi distribusi dan data tervalidasi.
            </p>
          </div>

          <ResponsiveContainer width="100%" height={280}>
            <BarChart data={distribusiData} barSize={24}>
              <CartesianGrid
                strokeDasharray="3 3"
                vertical={false}
                stroke="hsl(210 25% 88%)"
              />
              <XAxis
                dataKey="wilayah"
                fontSize={12}
                tickLine={false}
                axisLine={false}
              />
              <YAxis fontSize={12} tickLine={false} axisLine={false} />
              <Tooltip />
              <Bar
                dataKey="porsi"
                name="Porsi Distribusi"
                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>

      <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">Daftar SPPG Terpantau</h3>
          <p className="text-sm text-muted-foreground">
            Pemerintah dapat melihat detail SPPG, tetapi tidak dapat mengedit
            data.
          </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>
        ) : filteredSPPG.length === 0 ? (
          <div className="py-16 text-center text-sm text-muted-foreground">
            Tidak ada data SPPG yang sesuai filter.
          </div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead className="bg-muted/50">
                <tr>
                  <th className="px-4 py-3 text-left text-xs font-semibold text-muted-foreground">
                    Nama SPPG
                  </th>
                  <th className="px-4 py-3 text-left text-xs font-semibold text-muted-foreground">
                    Wilayah
                  </th>
                  <th className="px-4 py-3 text-right text-xs font-semibold text-muted-foreground">
                    Total Dana
                  </th>
                  <th className="px-4 py-3 text-right text-xs font-semibold text-muted-foreground">
                    Jumlah Siswa
                  </th>
                  <th className="px-4 py-3 text-center text-xs font-semibold text-muted-foreground">
                    Status
                  </th>
                  <th className="px-4 py-3 text-center text-xs font-semibold text-muted-foreground">
                    Aksi
                  </th>
                </tr>
              </thead>

              <tbody className="divide-y divide-border">
                {filteredSPPG.map((item) => (
                  <tr key={item.id} className="hover:bg-muted/30">
                    <td className="px-4 py-3 font-semibold text-foreground">
                      {item.nama || "-"}
                    </td>

                    <td className="px-4 py-3 text-muted-foreground">
                      {item.kabupaten || "-"}, {item.provinsi || "-"}
                    </td>

                    <td className="px-4 py-3 text-right font-semibold text-primary">
                      {formatRp(item.total_dana)}
                    </td>

                    <td className="px-4 py-3 text-right">
                      {(Number(item.jumlah_siswa) || 0).toLocaleString(
                        "id-ID"
                      )}
                    </td>

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

                    <td className="px-4 py-3 text-center">
                      <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>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>

      <div className="grid gap-6 lg:grid-cols-[1fr_1.2fr]">
        <div className="rounded-3xl border border-border bg-card p-5 shadow-sm">
          <h3 className="mb-4 font-bold text-foreground">
            Aktivitas Terbaru
          </h3>

          <div className="space-y-4">
            {aktivitasTerbaru.map((item, index) => (
              <div
                key={index}
                className="rounded-2xl border border-border bg-muted/20 p-4"
              >
                <div className="mb-2 flex items-start gap-3">
                  <div
                    className={`mt-1 h-3 w-3 rounded-full ${
                      item.tipe === "success"
                        ? "bg-emerald-500"
                        : item.tipe === "warning"
                        ? "bg-yellow-500"
                        : "bg-blue-500"
                    }`}
                  />

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

                <div className="mt-3 flex items-center justify-between gap-3">
                  <span
                    className={`rounded-full px-3 py-1 text-xs font-bold ${
                      item.tipe === "success"
                        ? "bg-emerald-100 text-emerald-700"
                        : item.tipe === "warning"
                        ? "bg-yellow-100 text-yellow-700"
                        : "bg-blue-100 text-blue-700"
                    }`}
                  >
                    {item.status}
                  </span>

                  <span className="flex items-center gap-1 text-xs font-semibold text-muted-foreground">
                    <Clock className="h-3.5 w-3.5" />
                    {item.waktu}
                  </span>
                </div>
              </div>
            ))}
          </div>
        </div>

        <div className="rounded-3xl border border-border bg-card p-5 shadow-sm">
          <div className="mb-4 flex items-start gap-3">
            <div className="flex h-11 w-11 items-center justify-center rounded-2xl bg-yellow-50 text-yellow-700">
              <AlertTriangle className="h-5 w-5" />
            </div>

            <div>
              <h3 className="font-bold text-foreground">
                Catatan Pengawasan Pemerintah
              </h3>
              <p className="text-sm text-muted-foreground">
                Ringkasan otomatis untuk membantu pemantauan program.
              </p>
            </div>
          </div>

          <div className="space-y-3 text-sm">
            <div className="rounded-2xl bg-blue-50 p-4 text-blue-800">
              Pemerintah dapat melihat seluruh data SPPG secara nasional, tetapi
              tidak memiliki akses untuk mengubah, menambah, atau menghapus data.
            </div>

            <div className="rounded-2xl bg-emerald-50 p-4 text-emerald-800">
              Fokus utama halaman ini adalah pengawasan status aktif SPPG,
              distribusi, laporan, dan penggunaan dana.
            </div>

            <div className="rounded-2xl bg-yellow-50 p-4 text-yellow-800">
              Jika ditemukan data tidak wajar, pemerintah dapat menindaklanjuti
              melalui admin atau pihak validator terkait.
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}