import { useEffect, useMemo, useState } from "react";
import {
  ShieldCheck,
  RefreshCw,
  Search,
  Radio,
  Users,
  CalendarDays,
  CalendarRange,
  BarChart3,
  Activity,
} from "lucide-react";

const AUDIT_API = "http://localhost/backend/api/audit/list.php";

const ROLE_OPTIONS = [
  { label: "Semua Role", value: "all" },
  { label: "Admin", value: "admin" },
  { label: "Pemerintah", value: "pemerintah" },
  { label: "Masyarakat", value: "masyarakat" },
  { label: "Pihak Sekolah", value: "validator" },
  { label: "SPPG", value: "sppg" },
  { label: "Publik", value: "publik" },
  { label: "Sistem", value: "sistem" },
];

const ROLE_LABELS = {
  admin: "Admin",
  pemerintah: "Pemerintah",
  sppg: "SPPG",
  validator: "Pihak Sekolah",
  masyarakat: "Masyarakat",
  publik: "Publik",
  sistem: "Sistem",
};

const ROLE_COLORS = {
  admin: "bg-purple-100 text-purple-700",
  pemerintah: "bg-blue-100 text-blue-700",
  sppg: "bg-emerald-100 text-emerald-700",
  validator: "bg-amber-100 text-amber-700",
  masyarakat: "bg-cyan-100 text-cyan-700",
  publik: "bg-gray-100 text-gray-600",
  sistem: "bg-slate-100 text-slate-700",
};

const normalizeRole = (role = "") => {
  const value = String(role || "").toLowerCase();

  if (value.includes("admin")) return "admin";
  if (value.includes("pemerintah")) return "pemerintah";
  if (value.includes("sppg")) return "sppg";
  if (value.includes("validator")) return "validator";
  if (value.includes("sekolah")) return "validator";
  if (value.includes("masyarakat")) return "masyarakat";
  if (value.includes("publik")) return "publik";
  if (value.includes("sistem")) return "sistem";

  return value || "sistem";
};

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

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

const isToday = (value) => {
  if (!value) return false;

  const date = new Date(value);
  const now = new Date();

  return (
    date.getDate() === now.getDate() &&
    date.getMonth() === now.getMonth() &&
    date.getFullYear() === now.getFullYear()
  );
};

const isThisWeek = (value) => {
  if (!value) return false;

  const date = new Date(value);
  const now = new Date();

  const startOfWeek = new Date(now);
  startOfWeek.setDate(now.getDate() - now.getDay());
  startOfWeek.setHours(0, 0, 0, 0);

  const endOfWeek = new Date(startOfWeek);
  endOfWeek.setDate(startOfWeek.getDate() + 7);

  return date >= startOfWeek && date < endOfWeek;
};

const isThisMonth = (value) => {
  if (!value) return false;

  const date = new Date(value);
  const now = new Date();

  return (
    date.getMonth() === now.getMonth() &&
    date.getFullYear() === now.getFullYear()
  );
};

export default function AuditLogPage() {
  const [logs, setLogs] = useState([]);
  const [search, setSearch] = useState("");
  const [selectedRole, setSelectedRole] = useState("all");
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");

  const loadAuditLog = async (showSpinner = true) => {
    try {
      if (showSpinner) {
        setLoading(true);
      }

      setError("");

      const res = await fetch(AUDIT_API);

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

      const result = await res.json();

      if (result.success && Array.isArray(result.data)) {
        setLogs(result.data);
      } else {
        setLogs([]);
      }
    } catch (err) {
      console.error("Gagal mengambil audit log:", err);
      setError("Gagal mengambil data audit log dari server");
      setLogs([]);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadAuditLog();

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

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

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

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

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

  const filteredLogs = useMemo(() => {
    const keyword = search.trim().toLowerCase();

    return logs.filter((log) => {
      const role = normalizeRole(log.role);
      const matchRole = selectedRole === "all" || role === selectedRole;

      const combined = [
        log.username,
        ROLE_LABELS[role] || role,
        log.aksi,
        log.target,
        log.keterangan,
        log.ip_address,
        log.created_at,
      ]
        .join(" ")
        .toLowerCase();

      const matchSearch = !keyword || combined.includes(keyword);

      return matchRole && matchSearch;
    });
  }, [logs, search, selectedRole]);

  const activeLogs = useMemo(() => {
    if (selectedRole === "all") return logs;

    return logs.filter((log) => normalizeRole(log.role) === selectedRole);
  }, [logs, selectedRole]);

  const summary = useMemo(() => {
    return {
      total: activeLogs.length,
      harian: activeLogs.filter((log) => isToday(log.created_at)).length,
      mingguan: activeLogs.filter((log) => isThisWeek(log.created_at)).length,
      bulanan: activeLogs.filter((log) => isThisMonth(log.created_at)).length,
    };
  }, [activeLogs]);

  const roleCounts = useMemo(() => {
    return ROLE_OPTIONS.filter((role) => role.value !== "all").map((role) => ({
      ...role,
      count: logs.filter((log) => normalizeRole(log.role) === role.value).length,
    }));
  }, [logs]);

  const selectedRoleLabel =
    ROLE_OPTIONS.find((role) => role.value === selectedRole)?.label || "Semua Role";

  return (
    <div className="p-4 sm:p-6 lg:p-8 max-w-7xl mx-auto space-y-6">
      <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">Audit Log</h1>
          <p className="text-sm text-muted-foreground mt-1">
            Riwayat aktivitas sistem dipisahkan berdasarkan role pengguna dan diperbarui otomatis.
          </p>

          <div className="mt-2 inline-flex items-center gap-1.5 rounded-full bg-emerald-50 px-3 py-1 text-xs font-semibold text-emerald-700">
            <Radio className="w-3.5 h-3.5" />
            Auto refresh aktif setiap 3 detik
          </div>
        </div>

        <button
          type="button"
          onClick={() => loadAuditLog(true)}
          className="w-fit inline-flex items-center gap-2 rounded-lg border px-4 py-2 text-sm font-medium hover:bg-muted"
        >
          <RefreshCw className={`w-4 h-4 ${loading ? "animate-spin" : ""}`} />
          Refresh
        </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>
      )}

      <div className="grid grid-cols-2 lg:grid-cols-4 gap-3">
        <div className="bg-card rounded-xl border border-border p-4">
          <div className="flex items-center justify-between gap-3">
            <p className="text-sm text-muted-foreground">Total Log</p>
            <Activity className="w-5 h-5 text-blue-600" />
          </div>
          <p className="text-2xl font-bold mt-1">
            {summary.total.toLocaleString("id-ID")}
          </p>
          <p className="text-xs text-muted-foreground mt-1">
            Filter: {selectedRoleLabel}
          </p>
        </div>

        <div className="bg-card rounded-xl border border-border p-4">
          <div className="flex items-center justify-between gap-3">
            <p className="text-sm text-muted-foreground">Harian</p>
            <CalendarDays className="w-5 h-5 text-emerald-600" />
          </div>
          <p className="text-2xl font-bold mt-1 text-emerald-600">
            {summary.harian.toLocaleString("id-ID")}
          </p>
          <p className="text-xs text-muted-foreground mt-1">Aktivitas hari ini</p>
        </div>

        <div className="bg-card rounded-xl border border-border p-4">
          <div className="flex items-center justify-between gap-3">
            <p className="text-sm text-muted-foreground">Mingguan</p>
            <CalendarRange className="w-5 h-5 text-amber-600" />
          </div>
          <p className="text-2xl font-bold mt-1 text-amber-600">
            {summary.mingguan.toLocaleString("id-ID")}
          </p>
          <p className="text-xs text-muted-foreground mt-1">Aktivitas minggu ini</p>
        </div>

        <div className="bg-card rounded-xl border border-border p-4">
          <div className="flex items-center justify-between gap-3">
            <p className="text-sm text-muted-foreground">Bulanan</p>
            <BarChart3 className="w-5 h-5 text-purple-600" />
          </div>
          <p className="text-2xl font-bold mt-1 text-purple-600">
            {summary.bulanan.toLocaleString("id-ID")}
          </p>
          <p className="text-xs text-muted-foreground mt-1">Aktivitas bulan ini</p>
        </div>
      </div>

      <div className="bg-card rounded-xl border border-border p-4">
        <div className="flex items-center gap-2 mb-3">
          <Users className="w-5 h-5 text-primary" />
          <h3 className="font-bold text-foreground">Filter Role</h3>
        </div>

        <div className="flex gap-2 overflow-x-auto pb-1">
          {ROLE_OPTIONS.map((role) => {
            const count =
              role.value === "all"
                ? logs.length
                : roleCounts.find((item) => item.value === role.value)?.count || 0;

            return (
              <button
                key={role.value}
                type="button"
                onClick={() => setSelectedRole(role.value)}
                className={`whitespace-nowrap rounded-xl px-4 py-2 text-sm font-bold transition ${
                  selectedRole === role.value
                    ? "bg-primary text-white shadow-sm"
                    : "bg-muted/60 text-muted-foreground hover:bg-primary/10 hover:text-primary"
                }`}
              >
                {role.label}
                <span className="ml-2 rounded-full bg-white/20 px-2 py-0.5 text-xs">
                  {count.toLocaleString("id-ID")}
                </span>
              </button>
            );
          })}
        </div>
      </div>

      <div className="bg-card rounded-xl border border-border overflow-hidden">
        <div className="p-5 border-b border-border space-y-4">
          <div className="flex flex-col lg:flex-row lg:items-center lg:justify-between gap-4">
            <div>
              <h3 className="font-bold text-foreground">Daftar Audit Log</h3>
              <p className="text-xs text-muted-foreground mt-1">
                Menampilkan {filteredLogs.length.toLocaleString("id-ID")} dari{" "}
                {logs.length.toLocaleString("id-ID")} aktivitas.
              </p>
            </div>

            <div className="relative w-full lg:max-w-md">
              <Search className="absolute left-3.5 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
              <input
                value={search}
                onChange={(e) => setSearch(e.target.value)}
                placeholder="Cari pengguna, role, aksi, target, keterangan, atau IP..."
                className="w-full rounded-xl border border-input bg-background pl-10 pr-3 py-2 text-sm"
              />
            </div>
          </div>
        </div>

        <div className="max-h-[560px] overflow-auto">
          <table className="w-full min-w-[1100px] text-sm">
            <thead className="sticky top-0 z-10 bg-muted/80 backdrop-blur border-b border-border">
              <tr>
                {[
                  "Waktu",
                  "Pengguna",
                  "Role",
                  "Aksi",
                  "Target",
                  "Keterangan",
                  "IP Address",
                ].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 bg-card">
              {loading ? (
                <tr>
                  <td colSpan="7" className="py-12">
                    <div className="flex justify-center">
                      <div className="w-8 h-8 border-4 border-primary/20 border-t-primary rounded-full animate-spin" />
                    </div>
                  </td>
                </tr>
              ) : filteredLogs.length === 0 ? (
                <tr>
                  <td colSpan="7" className="py-12 text-center text-sm text-muted-foreground">
                    Belum ada data audit log sesuai filter.
                  </td>
                </tr>
              ) : (
                filteredLogs.map((log) => {
                  const role = normalizeRole(log.role);

                  return (
                    <tr key={log.id} className="hover:bg-muted/30">
                      <td className="px-4 py-3 text-muted-foreground whitespace-nowrap">
                        {formatTanggal(log.created_at)}
                      </td>

                      <td className="px-4 py-3">
                        <div className="flex items-center gap-2">
                          <div className="w-7 h-7 bg-primary/10 rounded-full flex items-center justify-center">
                            <ShieldCheck className="w-3.5 h-3.5 text-primary" />
                          </div>

                          <span className="font-medium">
                            {log.username || "Sistem"}
                          </span>
                        </div>
                      </td>

                      <td className="px-4 py-3">
                        <span
                          className={`px-2 py-0.5 rounded-full text-xs font-semibold ${
                            ROLE_COLORS[role] || "bg-gray-100 text-gray-600"
                          }`}
                        >
                          {ROLE_LABELS[role] || log.role || "-"}
                        </span>
                      </td>

                      <td className="px-4 py-3 font-medium">
                        {log.aksi || "-"}
                      </td>

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

                      <td className="px-4 py-3 text-muted-foreground max-w-md">
                        <p className="line-clamp-2">
                          {log.keterangan || "-"}
                        </p>
                      </td>

                      <td className="px-4 py-3 text-muted-foreground whitespace-nowrap">
                        {log.ip_address || "-"}
                      </td>
                    </tr>
                  );
                })
              )}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}
