import { useState, useEffect } from "react";

const STORAGE_KEY = "mbg_notifications";

const defaultNotifications = [
  { id: 1, title: "SPPG Baru Terdaftar", message: "SPPG Berkah Jaya telah terdaftar dan menunggu verifikasi.", time: "5 menit lalu", read: false, type: "info" },
  { id: 2, title: "Laporan Menunggu Validasi", message: "Ada 3 laporan dari SPPG yang menunggu validasi Anda.", time: "20 menit lalu", read: false, type: "warning" },
  { id: 3, title: "Pengaduan Baru", message: "Pengaduan baru diterima dari masyarakat mengenai kualitas makanan.", time: "1 jam lalu", read: true, type: "alert" },
  { id: 4, title: "Data Berhasil Diverifikasi", message: "Laporan SPPG Sejahtera tanggal 29 Apr telah disetujui validator.", time: "2 jam lalu", read: true, type: "success" },
];

export function useNotifications() {
  const [notifications, setNotifications] = useState(() => {
    try {
      const saved = localStorage.getItem(STORAGE_KEY);
      return saved ? JSON.parse(saved) : defaultNotifications;
    } catch {
      return defaultNotifications;
    }
  });

  const unreadCount = notifications.filter((n) => !n.read).length;

  const markAllRead = () => {
    const updated = notifications.map((n) => ({ ...n, read: true }));
    setNotifications(updated);
    localStorage.setItem(STORAGE_KEY, JSON.stringify(updated));
  };

  const markRead = (id) => {
    const updated = notifications.map((n) => n.id === id ? { ...n, read: true } : n);
    setNotifications(updated);
    localStorage.setItem(STORAGE_KEY, JSON.stringify(updated));
  };

  const addNotification = (notif) => {
    const newNotif = { ...notif, id: Date.now(), read: false, time: "Baru saja" };
    const updated = [newNotif, ...notifications];
    setNotifications(updated);
    localStorage.setItem(STORAGE_KEY, JSON.stringify(updated));
  };

  return { notifications, unreadCount, markAllRead, markRead, addNotification };
}