import { useEffect, useState } from "react";
import {
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
  PieChart,
  Pie,
  Cell,
} from "recharts";

import StatCard from "../components/StatCard";
import VisitorStats from "../components/VisitorStats";
import SPPGBestByProvince from "../components/SPPGBestByProvince";

const SUMMARY_API = "http://localhost/backend/api/dashboard/summary.php";
const STATISTIK_API = "http://localhost/backend/api/statistik/summary.php";

const COLORS = [
  "#16a34a",
  "#2563eb",
  "#f59e0b",
  "#dc2626",
  "#7c3aed",
  "#0891b2",
  "#ea580c",
  "#65a30d",
];

const PENGADUAN_COLORS = {
  Baru: "#2563eb",
  Diproses: "#f59e0b",
  Selesai: "#16a34a",
};

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

const formatShortRp = (n) => {
  const value = Number(n) || 0;

  if (value >= 1000000000) {
    return `Rp ${(value / 1000000000).toFixed(1)} M`;
  }

  if (value >= 1000000) {
    return `Rp ${(value / 1000000).toFixed(1)} Jt`;
  }

  return formatRp(value);
};

const emptyStatistik = {
  sppg_per_wilayah: [],
  dana_per_sppg: [],
  siswa_per_sppg: [],
  pengaduan_status: [],
  distribusi: {
    total_porsi: 0,
    total_terdistribusi: 0,
    belum_tersalurkan: 0,
  },
  stok_bahan: [],
};

export default function Statistik() {
  const [summary, setSummary] = useState({
    total_sppg: 0,
    total_sekolah: 0,
    total_siswa: 0,
    total_dana: 0,
    total_pengaduan: 0,
    pengaduan_baru: 0,
    pengaduan_diproses: 0,
    pengaduan_selesai: 0,
  });

  const [statistik, setStatistik] = useState(emptyStatistik);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");

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

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

      const [summaryRes, statistikRes] = await Promise.all([
        fetch(SUMMARY_API),
        fetch(STATISTIK_API),
      ]);

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

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

      const summaryResult = await summaryRes.json();
      const statistikResult = await statistikRes.json();

      if (summaryResult.success && summaryResult.data) {
        setSummary({
          total_sppg: summaryResult.data.total_sppg || 0,
          total_sekolah: summaryResult.data.total_sekolah || 0,
          total_siswa: summaryResult.data.total_siswa || 0,
          total_dana: summaryResult.data.total_dana || 0,
          total_pengaduan: summaryResult.data.total_pengaduan || 0,
          pengaduan_baru: summaryResult.data.pengaduan_baru || 0,
          pengaduan_diproses: summaryResult.data.pengaduan_diproses || 0,
          pengaduan_selesai: summaryResult.data.pengaduan_selesai || 0,
        });
      }

      if (statistikResult.success && statistikResult.data) {
        setStatistik({
          ...emptyStatistik,
          ...statistikResult.data,
          distribusi: {
            ...emptyStatistik.distribusi,
            ...(statistikResult.data.distribusi || {}),
          },
        });
      } else {
        setStatistik(emptyStatistik);
      }
    } catch (err) {
      console.error("Gagal mengambil statistik:", err);
      setError("Gagal mengambil data statistik dari server");
      setStatistik(emptyStatistik);
    } finally {
      setLoading(false);
    }
  };

  const sppgWilayahData = statistik.sppg_per_wilayah || [];
  const danaSppgData = statistik.dana_per_sppg || [];
  const siswaSppgData = statistik.siswa_per_sppg || [];
  const pengaduanStatusData = statistik.pengaduan_status || [];
  const stokBahanData = statistik.stok_bahan || [];

  const distribusiData = [
    {
      name: "Terdistribusi",
      value: Number(statistik.distribusi.total_terdistribusi || 0),
    },
    {
      name: "Belum Tersalurkan",
      value: Number(statistik.distribusi.belum_tersalurkan || 0),
    },
  ];

  const persentaseDistribusi =
    Number(statistik.distribusi.total_porsi || 0) > 0
      ? (Number(statistik.distribusi.total_terdistribusi || 0) /
          Number(statistik.distribusi.total_porsi || 0)) *
        100
      : 0;

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-[60vh]">
        <div className="w-8 h-8 border-4 border-primary/20 border-t-primary rounded-full animate-spin" />
      </div>
    );
  }

  return (
    <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-10">
      <div className="mb-10">
        <div className="relative overflow-hidden rounded-[2.25rem] border border-white/10 bg-gradient-to-br from-[#23486b] via-[#2450d3] to-[#1b8d93] text-white shadow-[0_20px_70px_rgba(2,8,23,0.22)]">
          <div className="pointer-events-none absolute inset-0 bg-[linear-gradient(rgba(255,255,255,0.06)_1px,transparent_1px),linear-gradient(90deg,rgba(255,255,255,0.06)_1px,transparent_1px)] bg-[size:70px_70px] opacity-45" />
          <div className="pointer-events-none absolute inset-0 bg-[radial-gradient(circle_at_top_left,rgba(255,255,255,0.16),transparent_28%),radial-gradient(circle_at_top_right,rgba(96,165,250,0.18),transparent_24%),radial-gradient(circle_at_bottom_right,rgba(45,212,191,0.16),transparent_28%)]" />

          <div className="relative z-10 px-5 py-10 text-center sm:px-8 sm:py-12 lg:px-12 lg:py-16">
            <div className="inline-flex items-center rounded-full border border-white/15 bg-white/10 px-5 py-2 text-sm font-bold uppercase tracking-[0.18em] text-blue-50 shadow-lg backdrop-blur-md">
              Dashboard Nasional
            </div>

            <h1 className="mx-auto mt-6 max-w-full whitespace-nowrap text-3xl font-black leading-[1.05] tracking-tight text-white drop-shadow-[0_4px_16px_rgba(0,0,0,0.25)] sm:text-4xl lg:text-5xl xl:text-6xl">
              <span className="text-white">Statistik </span>
              <span className="bg-gradient-to-r from-cyan-200 via-sky-100 to-teal-200 bg-clip-text text-transparent">
                Nasional MBG
              </span>
            </h1>

            <p className="mx-auto mt-5 max-w-4xl text-base leading-relaxed text-blue-50/90 sm:text-lg lg:text-xl">
              Visualisasi data SPPG, dana, siswa, pengaduan, distribusi, dan stok bahan dari database MySQL dengan tampilan yang lebih jelas dan rapi.
            </p>

            <div className="mt-8 flex justify-center">
              <button
                type="button"
                onClick={loadStatistik}
                className="inline-flex items-center justify-center rounded-full border border-white/25 bg-white/10 px-6 py-3 text-sm font-bold text-white shadow-lg backdrop-blur-md transition hover:bg-white/20"
              >
                Refresh Data
              </button>
            </div>
          </div>
        </div>
      </div>

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

      <div className="mb-8">
        <VisitorStats title="Statistik Pengunjung Website" />
      </div>

      <div className="mb-8">
        <SPPGBestByProvince />
      </div>

      <div className="grid grid-cols-2 lg:grid-cols-4 gap-3 sm:gap-4 mb-8">
        <StatCard
          label="Total SPPG"
          value={Number(summary.total_sppg || 0).toLocaleString("id-ID")}
        />

        <StatCard
          label="Total Dana"
          value={formatShortRp(summary.total_dana)}
          color="text-emerald-600"
        />

        <StatCard
          label="Total Sekolah"
          value={Number(summary.total_sekolah || 0).toLocaleString("id-ID")}
          color="text-amber-600"
        />

        <StatCard
          label="Total Siswa"
          value={Number(summary.total_siswa || 0).toLocaleString("id-ID")}
          color="text-primary"
        />
      </div>

      <div className="grid grid-cols-2 lg:grid-cols-4 gap-3 sm:gap-4 mb-8">
        <StatCard
          label="Total Pengaduan"
          value={Number(summary.total_pengaduan || 0).toLocaleString("id-ID")}
          color="text-blue-600"
        />

        <StatCard
          label="Total Porsi"
          value={Number(statistik.distribusi.total_porsi || 0).toLocaleString("id-ID")}
          color="text-purple-600"
        />

        <StatCard
          label="Terdistribusi"
          value={Number(statistik.distribusi.total_terdistribusi || 0).toLocaleString("id-ID")}
          color="text-green-600"
        />

        <StatCard
          label="Distribusi"
          value={`${persentaseDistribusi.toFixed(1)}%`}
          color="text-emerald-600"
        />
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
        <div className="bg-card rounded-2xl border border-border/80 p-5 shadow-sm shadow-slate-200/60 transition hover:shadow-md sm:p-6">
          <h3 className="font-bold text-foreground mb-2">SPPG per Wilayah</h3>
          <p className="text-sm text-muted-foreground mb-4">
            Jumlah SPPG berdasarkan kabupaten/kota.
          </p>

          {sppgWilayahData.length === 0 ? (
            <div className="text-center py-16 text-sm text-muted-foreground">
              Belum ada data wilayah.
            </div>
          ) : (
            <div className="w-full h-80">
              <ResponsiveContainer width="100%" height="100%">
                <BarChart data={sppgWilayahData}>
                  <CartesianGrid strokeDasharray="3 3" stroke="#e5e7eb" />
                  <XAxis dataKey="name" tick={{ fontSize: 12 }} />
                  <YAxis tick={{ fontSize: 12 }} allowDecimals={false} />
                  <Tooltip />
                  <Bar
                    dataKey="value"
                    name="Jumlah SPPG"
                    fill="#16a34a"
                    radius={[8, 8, 0, 0]}
                  />
                </BarChart>
              </ResponsiveContainer>
            </div>
          )}
        </div>

        <div className="bg-card rounded-2xl border border-border/80 p-5 shadow-sm shadow-slate-200/60 transition hover:shadow-md sm:p-6">
          <h3 className="font-bold text-foreground mb-2">Dana per SPPG</h3>
          <p className="text-sm text-muted-foreground mb-4">
            Perbandingan total dana pada setiap SPPG.
          </p>

          {danaSppgData.length === 0 ? (
            <div className="text-center py-16 text-sm text-muted-foreground">
              Belum ada data dana SPPG.
            </div>
          ) : (
            <div className="w-full h-80">
              <ResponsiveContainer width="100%" height="100%">
                <BarChart data={danaSppgData}>
                  <CartesianGrid strokeDasharray="3 3" stroke="#e5e7eb" />
                  <XAxis dataKey="name" tick={{ fontSize: 11 }} interval={0} />
                  <YAxis
                    tickFormatter={(v) => `${v / 1000000}jt`}
                    tick={{ fontSize: 12 }}
                  />
                  <Tooltip
                    formatter={(value) => formatRp(value)}
                    labelFormatter={(label) => `SPPG: ${label}`}
                  />
                  <Bar
                    dataKey="value"
                    name="Total Dana"
                    fill="#2563eb"
                    radius={[8, 8, 0, 0]}
                  />
                </BarChart>
              </ResponsiveContainer>
            </div>
          )}
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
        <div className="bg-card rounded-2xl border border-border/80 p-5 shadow-sm shadow-slate-200/60 transition hover:shadow-md sm:p-6">
          <h3 className="font-bold text-foreground mb-2">Siswa per SPPG</h3>
          <p className="text-sm text-muted-foreground mb-4">
            Jumlah siswa penerima berdasarkan data sekolah tiap SPPG.
          </p>

          {siswaSppgData.length === 0 ? (
            <div className="text-center py-16 text-sm text-muted-foreground">
              Belum ada data siswa.
            </div>
          ) : (
            <div className="w-full h-80">
              <ResponsiveContainer width="100%" height="100%">
                <BarChart data={siswaSppgData}>
                  <CartesianGrid strokeDasharray="3 3" stroke="#e5e7eb" />
                  <XAxis dataKey="name" tick={{ fontSize: 11 }} interval={0} />
                  <YAxis tick={{ fontSize: 12 }} />
                  <Tooltip
                    formatter={(value) => Number(value || 0).toLocaleString("id-ID")}
                    labelFormatter={(label) => `SPPG: ${label}`}
                  />
                  <Bar
                    dataKey="value"
                    name="Total Siswa"
                    fill="#f59e0b"
                    radius={[8, 8, 0, 0]}
                  />
                </BarChart>
              </ResponsiveContainer>
            </div>
          )}
        </div>

        <div className="bg-card rounded-2xl border border-border/80 p-5 shadow-sm shadow-slate-200/60 transition hover:shadow-md sm:p-6">
          <h3 className="font-bold text-foreground mb-2">Stok Bahan Makanan</h3>
          <p className="text-sm text-muted-foreground mb-4">
            Bahan makanan diurutkan dari stok paling rendah.
          </p>

          {stokBahanData.length === 0 ? (
            <div className="text-center py-16 text-sm text-muted-foreground">
              Belum ada data bahan makanan.
            </div>
          ) : (
            <div className="w-full h-80">
              <ResponsiveContainer width="100%" height="100%">
                <BarChart data={stokBahanData}>
                  <CartesianGrid strokeDasharray="3 3" stroke="#e5e7eb" />
                  <XAxis dataKey="name" tick={{ fontSize: 12 }} />
                  <YAxis tick={{ fontSize: 12 }} />
                  <Tooltip
                    formatter={(value) => Number(value || 0).toLocaleString("id-ID")}
                  />
                  <Bar
                    dataKey="value"
                    name="Stok"
                    fill="#0891b2"
                    radius={[8, 8, 0, 0]}
                  />
                </BarChart>
              </ResponsiveContainer>
            </div>
          )}
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
        <div className="bg-card rounded-2xl border border-border/80 p-5 shadow-sm shadow-slate-200/60 transition hover:shadow-md sm:p-6">
          <h3 className="font-bold text-foreground mb-2">
            Komposisi Status Pengaduan
          </h3>

          <p className="text-sm text-muted-foreground mb-4">
            Perbandingan status laporan masyarakat.
          </p>

          {pengaduanStatusData.length === 0 ? (
            <div className="text-center py-16 text-sm text-muted-foreground">
              Belum ada data pengaduan.
            </div>
          ) : (
            <div className="w-full h-80">
              <ResponsiveContainer width="100%" height="100%">
                <PieChart>
                  <Pie
                    data={pengaduanStatusData}
                    dataKey="value"
                    nameKey="name"
                    outerRadius={110}
                    label
                  >
                    {pengaduanStatusData.map((entry, index) => (
                      <Cell
                        key={`cell-${index}`}
                        fill={PENGADUAN_COLORS[entry.name] || COLORS[index % COLORS.length]}
                      />
                    ))}
                  </Pie>
                  <Tooltip />
                </PieChart>
              </ResponsiveContainer>
            </div>
          )}
        </div>

        <div className="bg-card rounded-2xl border border-border/80 p-5 shadow-sm shadow-slate-200/60 transition hover:shadow-md sm:p-6">
          <h3 className="font-bold text-foreground mb-2">Distribusi Porsi</h3>
          <p className="text-sm text-muted-foreground mb-4">
            Perbandingan porsi yang sudah tersalurkan dan belum tersalurkan.
          </p>

          {Number(statistik.distribusi.total_porsi || 0) === 0 ? (
            <div className="text-center py-16 text-sm text-muted-foreground">
              Belum ada data distribusi.
            </div>
          ) : (
            <div className="w-full h-80">
              <ResponsiveContainer width="100%" height="100%">
                <PieChart>
                  <Pie
                    data={distribusiData}
                    dataKey="value"
                    nameKey="name"
                    outerRadius={110}
                    label
                  >
                    <Cell fill="#16a34a" />
                    <Cell fill="#dc2626" />
                  </Pie>
                  <Tooltip />
                </PieChart>
              </ResponsiveContainer>
            </div>
          )}
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
        <div className="bg-card rounded-2xl border border-border/80 p-5 shadow-sm shadow-slate-200/60 transition hover:shadow-md sm:p-6">
          <h3 className="font-bold text-foreground mb-2">Ringkasan Nasional</h3>
          <p className="text-sm text-muted-foreground mb-4">
            Kesimpulan singkat dari data utama yang tersimpan di sistem.
          </p>

          <div className="space-y-4">
            <div className="rounded-2xl bg-emerald-50 border border-emerald-100 p-4">
              <p className="text-sm text-emerald-700">Dana nasional tercatat</p>
              <p className="text-2xl font-bold text-emerald-700">
                {formatRp(summary.total_dana)}
              </p>
            </div>

            <div className="rounded-2xl bg-blue-50 border border-blue-100 p-4">
              <p className="text-sm text-blue-700">Rata-rata siswa per sekolah</p>
              <p className="text-2xl font-bold text-blue-700">
                {Number(summary.total_sekolah || 0) > 0
                  ? Math.round(
                      Number(summary.total_siswa || 0) /
                        Number(summary.total_sekolah || 1)
                    ).toLocaleString("id-ID")
                  : 0}
              </p>
            </div>

            <div className="rounded-2xl bg-amber-50 border border-amber-100 p-4">
              <p className="text-sm text-amber-700">Wilayah tercatat</p>
              <p className="text-2xl font-bold text-amber-700">
                {sppgWilayahData.length.toLocaleString("id-ID")}
              </p>
            </div>
          </div>
        </div>

        <div className="bg-card rounded-2xl border border-border/80 p-5 shadow-sm shadow-slate-200/60 transition hover:shadow-md sm:p-6">
          <h3 className="font-bold text-foreground mb-2">Catatan Statistik</h3>
          <p className="text-sm text-muted-foreground mb-4">
            Catatan otomatis berdasarkan data statistik terkini.
          </p>

          <div className="space-y-3 text-sm">
            <div className="rounded-2xl border border-slate-100 bg-muted/30 p-4">
              Distribusi porsi saat ini mencapai <b>{persentaseDistribusi.toFixed(1)}%</b>.
            </div>

            <div className="rounded-2xl border border-slate-100 bg-muted/30 p-4">
              Total porsi belum tersalurkan sebanyak{" "}
              <b>{Number(statistik.distribusi.belum_tersalurkan || 0).toLocaleString("id-ID")}</b> porsi.
            </div>

            <div className="rounded-2xl border border-slate-100 bg-muted/30 p-4">
              Bahan dengan stok paling rendah:{" "}
              <b>{stokBahanData[0]?.name || "Belum ada data"}</b>.
            </div>

            <div className="rounded-2xl border border-slate-100 bg-muted/30 p-4">
              SPPG dengan dana tertinggi:{" "}
              <b>{danaSppgData[0]?.name || "Belum ada data"}</b>.
            </div>
          </div>
        </div>
      </div>

      <div className="bg-card rounded-2xl border border-border/80 overflow-hidden shadow-sm shadow-slate-200/60">
        <div className="p-5 border-b border-border">
          <h3 className="font-bold text-foreground">Tabel Dana per SPPG</h3>
          <p className="text-sm text-muted-foreground mt-1">
            Data total dana berdasarkan setiap SPPG.
          </p>
        </div>

        {danaSppgData.length === 0 ? (
          <div className="text-center py-16 text-sm text-muted-foreground">
            Belum ada data dana SPPG.
          </div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead className="bg-primary/5">
                <tr>
                  <th className="text-left px-4 py-3 font-semibold">Nama SPPG</th>
                  <th className="text-right px-4 py-3 font-semibold">Total Dana</th>
                </tr>
              </thead>

              <tbody className="divide-y divide-border">
                {danaSppgData.map((item, index) => (
                  <tr key={`${item.name}-${index}`} className="hover:bg-muted/30">
                    <td className="px-4 py-3 font-medium">
                      <span
                        className="inline-block w-3 h-3 rounded-full mr-2"
                        style={{ backgroundColor: COLORS[index % COLORS.length] }}
                      />
                      {item.name || "-"}
                    </td>
                    <td className="px-4 py-3 text-right font-semibold text-primary">
                      {formatRp(item.value)}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </div>
  );
}
