import { create } from 'zustand';
import type { AppNotification, NotificationData } from '@/types/chat';

const MAX_NOTIFICATIONS = 50;

interface NotificationStore {
  notifications: AppNotification[];
  unreadCount: number;
  isOpen: boolean;

  addNotification: (data: NotificationData) => void;
  markAsRead: (id: string) => void;
  markAllAsRead: () => void;
  removeNotification: (id: string) => void;
  clearAll: () => void;
  toggleOpen: () => void;
  setOpen: (open: boolean) => void;
}

export const useNotificationStore = create<NotificationStore>((set) => ({
  notifications: [],
  unreadCount: 0,
  isOpen: false,

  addNotification: (data: NotificationData) =>
    set((state) => {
      const existing = state.notifications.find((n) => n.id === data.id);
      if (existing) return state;

      const newNotif: AppNotification = {
        ...data,
        read: false,
        createdAt: Date.now(),
      };

      const notifications = [newNotif, ...state.notifications].slice(0, MAX_NOTIFICATIONS);
      const unreadCount = notifications.filter((n) => !n.read).length;

      return { notifications, unreadCount };
    }),

  markAsRead: (id: string) =>
    set((state) => {
      const notifications = state.notifications.map((n) =>
        n.id === id ? { ...n, read: true } : n
      );
      const unreadCount = notifications.filter((n) => !n.read).length;
      return { notifications, unreadCount };
    }),

  markAllAsRead: () =>
    set((state) => ({
      notifications: state.notifications.map((n) => ({ ...n, read: true })),
      unreadCount: 0,
    })),

  removeNotification: (id: string) =>
    set((state) => {
      const notifications = state.notifications.filter((n) => n.id !== id);
      const unreadCount = notifications.filter((n) => !n.read).length;
      return { notifications, unreadCount };
    }),

  clearAll: () => set({ notifications: [], unreadCount: 0, isOpen: false }),

  toggleOpen: () => set((state) => ({ isOpen: !state.isOpen })),

  setOpen: (open: boolean) => set({ isOpen: open }),
}));
