import { createEvent, createStore } from 'effector'

type NotificationType = 'success' | 'error' | 'info' | 'warning'

export interface Notification {
  id: string
  type: NotificationType
  message: string
  autoHideDuration?: number
  actionLabel?: string
  actionPath?: string
}

const MAX_VISIBLE = 3
let nextId = 1

export const addNotification = createEvent<{
  type: NotificationType
  message: string
  autoHideDuration?: number
  actionLabel?: string
  actionPath?: string
}>()

export const dismissNotification = createEvent<string>()
export const dismissAll = createEvent()

export const $notifications = createStore<Notification[]>([])
  .on(addNotification, (state, { type, message, autoHideDuration, actionLabel, actionPath }) => {
    const notification: Notification = {
      id: String(nextId++),
      type,
      message,
      autoHideDuration: autoHideDuration ?? (type === 'error' ? 6000 : 4000),
      actionLabel,
      actionPath,
    }
    return [...state, notification].slice(-MAX_VISIBLE)
  })
  .on(dismissNotification, (state, id) => state.filter((n) => n.id !== id))
  .reset(dismissAll)
