import { create } from 'zustand';
import { notificationsApi, type Notification } from '@/lib/api';
import { toast } from 'sonner';

interface NotificationsState {
    notifications: Notification[];
    unreadCount: number;
    loading: boolean;
    fetchNotifications: () => Promise<void>;
    markAsRead: (id: string) => Promise<void>;
    markAllAsRead: () => Promise<void>;
}

export const useNotificationsStore = create<NotificationsState>((set, get) => ({
    notifications: [],
    unreadCount: 0,
    loading: false,

    fetchNotifications: async () => {
        set({ loading: true });
        try {
            const data = await notificationsApi.list();
            set({
                notifications: data || [],
                unreadCount: (data || []).filter((n) => !n.readAt).length,
            });
        } catch (error) {
            console.error("Failed to fetch notifications", error);
        } finally {
            set({ loading: false });
        }
    },

    markAsRead: async (id: string) => {
        try {
            // Optimistic update
            const { notifications, unreadCount } = get();
            const notification = notifications.find((n) => n.id === id);
            if (!notification || notification.readAt) return;

            set({
                notifications: notifications.map((n) =>
                    n.id === id ? { ...n, readAt: new Date().toISOString() } : n
                ),
                unreadCount: Math.max(0, unreadCount - 1),
            });

            await notificationsApi.markAsRead(id);
        } catch (error) {
            console.error("Failed to mark notification as read", error);
            // Revert on error could be implemented here
        }
    },

    markAllAsRead: async () => {
        try {
            // Optimistic update
            const { notifications } = get();
            set({
                notifications: notifications.map((n) => ({ ...n, readAt: new Date().toISOString() })),
                unreadCount: 0,
            });
            await notificationsApi.markAllAsRead();
            toast.success("All notifications marked as read");
        } catch (error) {
            console.error("Failed to mark all as read", error);
        }
    },
}));
