import { useState, useEffect } from "react";
import {
  Users,
  Database,
  AlertCircle,
  ShieldCheck,
  School,
  Wallet,
  MessageSquare,
  CheckCircle,
  Clock,
  Bell,
  UserRound,
  Package,
  Utensils,
  ClipboardList,
  TrendingUp,
} from "lucide-react";
import { Link } from "react-router-dom";

import StatCard from "../../components/StatCard";
import VisitorStats from "../../components/VisitorStats";
import { createAuditLog } from "../../utils/auditLogger";

const SUMMARY_API = "http://localhost/backend/api/dashboard/summary.php";
const SPPG_LIST_API = "http://localhost/backend/api/sppg/list.php";
const AUDIT_LIST_API = "http://localhost/backend/api/audit/list.php";

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

const defaultSummary = {
  total_sppg: 0,
  total_sekolah: 0,
  total_siswa: 0,
  total_dana: 0,

  total_karyawan: 0,
  total_gaji_karyawan: 0,
  total_bahan: 0,
  total_nilai_bahan: 0,
  total_barang_omprengan: 0,
  total_omprengan: 0,
  total_laporan: 0,
  total_porsi: 0,
  total_terdistribusi: 0,
  persentase_distribusi: 0,

  total_pengaduan: 0,
  pengaduan_baru: 0,
  pengaduan_diproses: 0,
  pengaduan_selesai: 0,
};

export default function AdminDashboard() {
  const [summary, setSummary] = useState(defaultSummary);
  const [sppgList, setSppgList] = useState([]);
  const [activityLogs, setActivityLogs] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");

  useEffect(() => {
    loadDashboard();
    loadAuditLogs(false);

    createAuditLog({
      aksi: "Membuka Dashboard",
      target: "Dashboard Admin",
      keterangan: "Admin membuka halaman dashboard utama.",
    });

    const handleAuditCreated = () => {
      loadAuditLogs(false);
    };

    const handleFocus = () => {
      loadAuditLogs(false);
    };

    window.addEventListener("audit-log-created", handleAuditCreated);
    window.addEventListener("focus", handleFocus);

    const interval = setInterval(() => {
      loadAuditLogs(false);
    }, 3000);

    return () => {
      window.removeEventListener("audit-log-created", handleAuditCreated);
      window.removeEventListener("focus", handleFocus);
      clearInterval(interval);
    };
  }, []);


  const formatAuditTime = (value) => {
    if (!value) return "-";

    return new Date(value).toLocaleString("id-ID", {
      day: "2-digit",
      month: "short",
      hour: "2-digit",
      minute: "2-digit",
    });
  };

  const loadAuditLogs = async () => {
    try {
      const res = await fetch(AUDIT_LIST_API);

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

      const result = await res.json();

      if (result.success && Array.isArray(result.data)) {
        setActivityLogs(result.data.slice(0, 5));
      } else {
        setActivityLogs([]);
      }
    } catch (err) {
      console.error("Gagal mengambil audit log dashboard:", err);
      setActivityLogs([]);
    }
  };

  const loadDashboard = async (isManualRefresh = false) => {
    try {
      setLoading(true);
      setError("");

      const [summaryRes, sppgRes] = await Promise.all([
        fetch(SUMMARY_API),
        fetch(SPPG_LIST_API),
      ]);

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

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

      const summaryResult = await summaryRes.json();
      const sppgResult = await sppgRes.json();

      if (summaryResult.success && summaryResult.data) {
        setSummary({
          ...defaultSummary,
          ...summaryResult.data,
        });
      } else {
        setSummary(defaultSummary);
      }

      if (sppgResult.success && Array.isArray(sppgResult.data)) {
        setSppgList(sppgResult.data);
      } else {
        setSppgList([]);
      }

      if (isManualRefresh) {
        createAuditLog({
          aksi: "Refresh Dashboard",
          target: "Dashboard Admin",
          keterangan: "Admin memperbarui data dashboard secara manual.",
        });
      }
    } catch (err) {
      console.error("Gagal mengambil data dashboard:", err);
      setError("Gagal mengambil data dashboard dari server");
      setSummary(defaultSummary);
      setSppgList([]);

      createAuditLog({
        aksi: "Gagal Memuat Dashboard",
        target: "Dashboard Admin",
        keterangan: "Sistem gagal mengambil data dashboard dari server.",
      });
    } finally {
      setLoading(false);
    }
  };

  const quickActions = [
    {
      icon: Database,
      label: "Data SPPG",
      path: "/admin/sppg",
      color: "bg-blue-50 text-blue-600",
    },
    {
      icon: School,
      label: "Data Sekolah",
      path: "/admin/sppg",
      color: "bg-emerald-50 text-emerald-600",
    },
    {
      icon: AlertCircle,
      label: "Pengaduan",
      path: "/admin/pengaduan",
      color: "bg-amber-50 text-amber-600",
    },
    {
      icon: Users,
      label: "Manajemen User",
      path: "/admin/users",
      color: "bg-purple-50 text-purple-600",
    },
  ];

  const belumTersalurkan = Math.max(
    Number(summary.total_porsi || 0) - Number(summary.total_terdistribusi || 0),
    0
  );

  const statusDistribusi =
    Number(summary.total_porsi || 0) === 0
      ? "Belum Ada Data"
      : Number(summary.persentase_distribusi || 0) >= 95
      ? "Sangat Baik"
      : Number(summary.persentase_distribusi || 0) >= 80
      ? "Cukup Baik"
      : "Perlu Evaluasi";

  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="p-4 sm:p-6 lg:p-8 max-w-7xl mx-auto space-y-8">
      <div className="flex flex-col sm:flex-row sm:items-start sm:justify-between gap-4">
        <div>
          <h1 className="text-2xl font-black text-foreground">
            Dashboard Admin
          </h1>

          <p className="text-sm text-muted-foreground mt-1">
            Ringkasan data sistem MBG dari database MySQL.
          </p>
        </div>

        <button
          type="button"
          onClick={() => loadDashboard(true)}
          className="w-fit rounded-lg border px-4 py-2 text-sm font-medium hover:bg-muted"
        >
          Refresh Data
        </button>
      </div>

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

      <VisitorStats mode="compact" title="Ringkasan Pengunjung Website" />

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

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

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

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

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

        <StatCard
          label="Total Gaji"
          value={formatRp(summary.total_gaji_karyawan)}
          color="text-pink-600"
        />

        <StatCard
          label="Bahan Makanan"
          value={Number(summary.total_bahan || 0).toLocaleString("id-ID")}
          color="text-orange-600"
        />

        <StatCard
          label="Nilai Stok Bahan"
          value={formatRp(summary.total_nilai_bahan)}
          color="text-emerald-600"
        />

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

        <StatCard
          label="Laporan Operasional"
          value={Number(summary.total_laporan || 0).toLocaleString("id-ID")}
          color="text-indigo-600"
        />

        <StatCard
          label="Distribusi Porsi"
          value={`${Number(summary.persentase_distribusi || 0).toLocaleString("id-ID")}%`}
          color="text-green-600"
        />

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

        <StatCard
          label="Pengaduan Baru"
          value={Number(summary.pengaduan_baru || 0).toLocaleString("id-ID")}
          color="text-red-600"
        />

        <StatCard
          label="Diproses"
          value={Number(summary.pengaduan_diproses || 0).toLocaleString("id-ID")}
          color="text-yellow-600"
        />

        <StatCard
          label="Selesai"
          value={Number(summary.pengaduan_selesai || 0).toLocaleString("id-ID")}
          color="text-green-600"
        />
      </div>

      <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
        {quickActions.map((item) => (
          <Link
            key={item.path + item.label}
            to={item.path}
            className="bg-card rounded-xl border border-border p-4 hover:shadow-md transition-all flex flex-col items-center gap-3 text-center group"
          >
            <div
              className={`w-12 h-12 rounded-xl flex items-center justify-center ${item.color}`}
            >
              <item.icon className="w-6 h-6" />
            </div>

            <p className="font-semibold text-sm text-foreground group-hover:text-primary">
              {item.label}
            </p>
          </Link>
        ))}
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-5">
        <div className="bg-card rounded-xl border border-border p-5">
          <div className="flex items-center gap-3 mb-4">
            <div className="w-10 h-10 rounded-xl bg-purple-50 flex items-center justify-center">
              <UserRound className="w-5 h-5 text-purple-600" />
            </div>
            <div>
              <h3 className="font-bold text-foreground">Ringkasan Karyawan</h3>
              <p className="text-xs text-muted-foreground">
                Total tenaga kerja dan gaji.
              </p>
            </div>
          </div>

          <p className="text-3xl font-black text-purple-600">
            {Number(summary.total_karyawan || 0).toLocaleString("id-ID")}
          </p>

          <p className="text-sm text-muted-foreground mt-2">
            Total gaji tercatat: <b>{formatRp(summary.total_gaji_karyawan)}</b>
          </p>
        </div>

        <div className="bg-card rounded-xl border border-border p-5">
          <div className="flex items-center gap-3 mb-4">
            <div className="w-10 h-10 rounded-xl bg-orange-50 flex items-center justify-center">
              <Package className="w-5 h-5 text-orange-600" />
            </div>
            <div>
              <h3 className="font-bold text-foreground">Ringkasan Bahan</h3>
              <p className="text-xs text-muted-foreground">
                Stok bahan makanan dapur.
              </p>
            </div>
          </div>

          <p className="text-3xl font-black text-orange-600">
            {Number(summary.total_bahan || 0).toLocaleString("id-ID")}
          </p>

          <p className="text-sm text-muted-foreground mt-2">
            Nilai stok: <b>{formatRp(summary.total_nilai_bahan)}</b>
          </p>
        </div>

        <div className="bg-card rounded-xl border border-border p-5">
          <div className="flex items-center gap-3 mb-4">
            <div className="w-10 h-10 rounded-xl bg-cyan-50 flex items-center justify-center">
              <Utensils className="w-5 h-5 text-cyan-600" />
            </div>
            <div>
              <h3 className="font-bold text-foreground">Ringkasan Omprengan</h3>
              <p className="text-xs text-muted-foreground">
                Wadah makan dan peralatan distribusi.
              </p>
            </div>
          </div>

          <p className="text-3xl font-black text-cyan-600">
            {Number(summary.total_omprengan || 0).toLocaleString("id-ID")}
          </p>

          <p className="text-sm text-muted-foreground mt-2">
            {Number(summary.total_barang_omprengan || 0).toLocaleString("id-ID")} jenis barang tercatat.
          </p>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <div className="bg-card rounded-xl border border-border p-5 lg:col-span-2">
          <div className="flex items-center justify-between gap-4 mb-5">
            <div className="flex items-center gap-3">
              <div className="w-10 h-10 rounded-xl bg-green-50 flex items-center justify-center">
                <TrendingUp className="w-5 h-5 text-green-600" />
              </div>
              <div>
                <h3 className="font-bold text-foreground">
                  Distribusi Porsi
                </h3>
                <p className="text-xs text-muted-foreground">
                  Perbandingan porsi dibuat dan porsi tersalurkan.
                </p>
              </div>
            </div>

            <span className="px-2 py-0.5 rounded-full bg-green-100 text-green-700 text-xs font-semibold">
              {statusDistribusi}
            </span>
          </div>

          <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
            <div className="rounded-lg bg-muted/30 p-4">
              <p className="text-sm text-muted-foreground">Total Porsi</p>
              <p className="text-xl font-bold">
                {Number(summary.total_porsi || 0).toLocaleString("id-ID")}
              </p>
            </div>

            <div className="rounded-lg bg-muted/30 p-4">
              <p className="text-sm text-muted-foreground">Terdistribusi</p>
              <p className="text-xl font-bold">
                {Number(summary.total_terdistribusi || 0).toLocaleString("id-ID")}
              </p>
            </div>

            <div className="rounded-lg bg-muted/30 p-4">
              <p className="text-sm text-muted-foreground">Belum Tersalurkan</p>
              <p className="text-xl font-bold">
                {belumTersalurkan.toLocaleString("id-ID")}
              </p>
            </div>
          </div>

          <div className="mt-4 rounded-lg bg-primary/5 border border-primary/10 p-4">
            <div className="flex items-center gap-2 mb-2">
              <ClipboardList className="w-4 h-4 text-primary" />
              <p className="text-sm font-semibold">Persentase Distribusi</p>
            </div>
            <p className="text-3xl font-black text-primary">
              {Number(summary.persentase_distribusi || 0).toLocaleString("id-ID")}%
            </p>
          </div>
        </div>

        <div className="bg-card rounded-xl border border-border p-5">
          <div className="flex items-center gap-3 mb-4">
            <div className="w-10 h-10 rounded-xl bg-primary/10 flex items-center justify-center">
              <Wallet className="w-5 h-5 text-primary" />
            </div>

            <div>
              <h3 className="font-bold text-foreground">
                Ringkasan Dana
              </h3>

              <p className="text-xs text-muted-foreground">
                Total dana seluruh SPPG.
              </p>
            </div>
          </div>

          <p className="text-3xl font-black text-primary">
            {formatRp(summary.total_dana)}
          </p>

          <p className="text-sm text-muted-foreground mt-3">
            Data dihitung otomatis dari kolom <b>total_dana</b> pada tabel SPPG.
          </p>
        </div>

        <div className="bg-card rounded-xl border border-border p-5">
          <div className="flex items-center gap-3 mb-4">
            <div className="w-10 h-10 rounded-xl bg-amber-50 flex items-center justify-center">
              <MessageSquare className="w-5 h-5 text-amber-600" />
            </div>

            <div>
              <h3 className="font-bold text-foreground">
                Ringkasan Pengaduan
              </h3>

              <p className="text-xs text-muted-foreground">
                Status laporan masyarakat.
              </p>
            </div>
          </div>

          <div className="space-y-3">
            <div className="flex items-center justify-between text-sm">
              <span className="flex items-center gap-2">
                <Bell className="w-4 h-4 text-red-600" />
                Baru
              </span>
              <b>{summary.pengaduan_baru}</b>
            </div>

            <div className="flex items-center justify-between text-sm">
              <span className="flex items-center gap-2">
                <Clock className="w-4 h-4 text-yellow-600" />
                Diproses
              </span>
              <b>{summary.pengaduan_diproses}</b>
            </div>

            <div className="flex items-center justify-between text-sm">
              <span className="flex items-center gap-2">
                <CheckCircle className="w-4 h-4 text-green-600" />
                Selesai
              </span>
              <b>{summary.pengaduan_selesai}</b>
            </div>
          </div>

          <Link
            to="/admin/pengaduan"
            className="inline-block mt-4 text-sm text-primary hover:underline"
          >
            Kelola pengaduan →
          </Link>
        </div>

        <div className="bg-card rounded-xl border border-border overflow-hidden">
          <div className="p-5 border-b border-border flex items-center justify-between">
            <h3 className="font-bold text-foreground">
              Log Aktivitas Sistem
            </h3>

            <Link
              to="/admin/audit-log"
              className="text-xs text-primary hover:underline"
            >
              Lihat semua →
            </Link>
          </div>

          <div className="divide-y divide-border">
            {activityLogs.length === 0 ? (
              <div className="px-5 py-8 text-center text-sm text-muted-foreground">
                Belum ada aktivitas terbaru.
              </div>
            ) : (
              activityLogs.map((log) => (
                <div
                  key={log.id}
                  className="flex items-start gap-3 px-5 py-3"
                >
                  <div className="w-8 h-8 bg-primary/10 rounded-full flex items-center justify-center flex-shrink-0 mt-0.5">
                    <ShieldCheck className="w-4 h-4 text-primary" />
                  </div>

                  <div className="flex-1 min-w-0">
                    <p className="text-sm font-medium text-foreground">
                      {log.aksi || "-"}
                    </p>

                    <p className="text-xs text-muted-foreground">
                      {log.username || "Sistem"} → {log.target || "-"}
                    </p>
                  </div>

                  <p className="text-xs text-muted-foreground flex-shrink-0">
                    {formatAuditTime(log.created_at)}
                  </p>
                </div>
              ))
            )}
          </div>
        </div>
      </div>

      <div className="bg-card rounded-xl border border-border overflow-hidden">
        <div className="p-5 border-b border-border flex items-center justify-between">
          <h3 className="font-bold text-foreground">
            SPPG Terdaftar
          </h3>

          <Link
            to="/admin/sppg"
            className="text-xs text-primary hover:underline"
          >
            Kelola →
          </Link>
        </div>

        {sppgList.length === 0 ? (
          <div className="py-12 text-center text-sm text-muted-foreground">
            Belum ada data SPPG.
          </div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead className="bg-muted/50">
                <tr>
                  {[
                    "Nama",
                    "Provinsi",
                    "Kab/Kota",
                    "Status",
                    "Total Dana",
                    "Aksi",
                  ].map((h) => (
                    <th
                      key={h}
                      className="text-left px-4 py-3 text-xs font-semibold text-muted-foreground"
                    >
                      {h}
                    </th>
                  ))}
                </tr>
              </thead>

              <tbody className="divide-y divide-border">
                {sppgList.slice(0, 5).map((s) => (
                  <tr
                    key={s.id}
                    className="hover:bg-muted/30"
                  >
                    <td className="px-4 py-3 font-medium">
                      {s.nama || "-"}
                    </td>

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

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

                    <td className="px-4 py-3">
                      <span
                        className={`px-2 py-0.5 rounded-full text-xs font-semibold ${
                          s.status === "Aktif"
                            ? "bg-emerald-100 text-emerald-700"
                            : "bg-gray-100 text-gray-600"
                        }`}
                      >
                        {s.status || "-"}
                      </span>
                    </td>

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

                    <td className="px-4 py-3">
                      <Link
                        to={`/detail-sppg/${s.id}`}
                        className="text-xs text-primary hover:underline"
                      >
                        Detail
                      </Link>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </div>
  );
}
