import type { PayloadAction } from "@reduxjs/toolkit"

import { createSlice } from "@reduxjs/toolkit"

const MAX_ITEMS = 50

export interface NotificationItem {
	event: string
	notification_id: string | null
	job_id: string | null
	project_id: string | null
	job_type: string | null
	status: string | null
	progress_pct: number | null
	message: string | null
	title: string | null
	created_at: string | null
	is_read?: boolean
}

interface NotificationsState {
	items: NotificationItem[]
	unreadCount: number
}

const initialState: NotificationsState = {
	items: [],
	unreadCount: 0,
}

const notificationsSlice = createSlice({
	name: "notifications",
	initialState,
	reducers: {
		addNotification(state, action: PayloadAction<NotificationItem>) {
			const incoming = action.payload
			// Update existing item for same job_id if it's a progress update
			const existingIdx = state.items.findIndex(
				(n) => n.job_id && n.job_id === incoming.job_id,
			)
			if (existingIdx !== -1) {
				state.items[existingIdx] = { ...state.items[existingIdx], ...incoming }
			} else {
				state.items.unshift(incoming)
			}
			// Cap at MAX_ITEMS
			if (state.items.length > MAX_ITEMS) {
				state.items = state.items.slice(0, MAX_ITEMS)
			}
			// Recalculate unread
			state.unreadCount = state.items.filter((n) => !n.is_read).length
		},
		markRead(state, action: PayloadAction<string>) {
			const item = state.items.find(
				(n) => n.notification_id === action.payload,
			)
			if (item) {
				item.is_read = true
			}
			state.unreadCount = state.items.filter((n) => !n.is_read).length
		},
		markAllRead(state) {
			state.items.forEach((n) => {
				n.is_read = true
			})
			state.unreadCount = 0
		},
		setNotifications(state, action: PayloadAction<NotificationItem[]>) {
			state.items = action.payload.slice(0, MAX_ITEMS)
			state.unreadCount = state.items.filter((n) => !n.is_read).length
		},
		resetNotifications() {
			return initialState
		},
	},
})

export const {
	addNotification,
	markRead,
	markAllRead,
	setNotifications,
	resetNotifications,
} = notificationsSlice.actions
export const notificationsReducer = notificationsSlice.reducer
