import { useState, useEffect } from "react"

// Simple event bus for toasts
const listeners: Array<(state: State) => void> = []

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

interface Toast {
  id: string
  title?: string
  description?: string
  type?: ToastType
  duration?: number
}

interface State {
  toasts: Toast[]
}

let memoryState: State = { toasts: [] }

function dispatch(action: State) {
  memoryState = { ...action }
  listeners.forEach((listener) => {
    listener(memoryState)
  })
}

function toast({ ...props }: Omit<Toast, "id">) {
  const id = Math.random().toString(36).substring(2, 9)
  const newToast = { ...props, id }
  
  dispatch({
    toasts: [...memoryState.toasts, newToast],
  })

  if (props.duration !== Infinity) {
     setTimeout(() => {
        dismiss(id)
     }, props.duration || 3000)
  }

  return {
    id,
    dismiss: () => dismiss(id),
    update: (props: Partial<Toast>) =>
      dispatch({
        toasts: memoryState.toasts.map((t) =>
          t.id === id ? { ...t, ...props } : t
        ),
      }),
  }
}

function dismiss(toastId?: string) {
  dispatch({
    toasts: memoryState.toasts.filter((t) => t.id !== toastId),
  })
}

export function useToast() {
  const [state, setState] = useState<State>(memoryState)

  useEffect(() => {
    listeners.push(setState)
    return () => {
      const index = listeners.indexOf(setState)
      if (index > -1) {
        listeners.splice(index, 1)
      }
    }
  }, [state])

  return {
    ...state,
    toast,
    dismiss,
  }
}

