import { useState } from "react";

const STORAGE_KEY = "mbg_audit_log";

const defaultLogs = [
  { id: 1, actor: "Admin", action: "Menambahkan SPPG baru", target: "SPPG Sejahtera", time: "30 Apr 2026, 10:23", role: "admin" },
  { id: 2, actor: "Validator Budi", action: "Menyetujui laporan", target: "Laporan #L-2024-001", time: "29 Apr 2026, 14:10", role: "validator" },
  { id: 3, actor: "Operator SPPG", action: "Input data harian", target: "SPPG Maju Mandiri", time: "29 Apr 2026, 09:45", role: "sppg" },
  { id: 4, actor: "Admin", action: "Memperbarui status pengaduan", target: "Pengaduan #P-001", time: "28 Apr 2026, 16:00", role: "admin" },
  { id: 5, actor: "Pemerintah", action: "Mengunduh laporan", target: "Laporan Q1 2024", time: "28 Apr 2026, 11:30", role: "pemerintah" },
];

export function useAuditLog() {
  const [logs, setLogs] = useState(() => {
    try {
      const saved = localStorage.getItem(STORAGE_KEY);
      return saved ? JSON.parse(saved) : defaultLogs;
    } catch {
      return defaultLogs;
    }
  });

  const addLog = (entry) => {
    const newEntry = { ...entry, id: Date.now(), time: new Date().toLocaleString("id-ID") };
    const updated = [newEntry, ...logs].slice(0, 100);
    setLogs(updated);
    localStorage.setItem(STORAGE_KEY, JSON.stringify(updated));
  };

  return { logs, addLog };
}