"use client"

import * as React from "react"

const TOAST_LIMIT = 5
const TOAST_REMOVE_DELAY = 2500

type ToastVariant = "default" | "success" | "error" | "warning" | "info"

type Toast = {
  id: string
  title?: React.ReactNode
  description?: React.ReactNode
  action?: React.ReactNode
  variant?: ToastVariant
}

const actionTypes = {
  ADD_TOAST: "ADD_TOAST",
  UPDATE_TOAST: "UPDATE_TOAST",
  DISMISS_TOAST: "DISMISS_TOAST",
  REMOVE_TOAST: "REMOVE_TOAST",
} as const

let count = 0

function genId() {
  count = (count + 1) % Number.MAX_SAFE_INTEGER
  return count.toString()
}

type ActionType =
  | { type: typeof actionTypes.ADD_TOAST; toast: Toast }
  | { type: typeof actionTypes.UPDATE_TOAST; toast: Partial<Toast> }
  | { type: typeof actionTypes.DISMISS_TOAST; toastId?: string }
  | { type: typeof actionTypes.REMOVE_TOAST; toastId?: string }

interface State {
  toasts: Toast[]
}

const listeners: Array<(state: State) => void> = []

let memoryState: State = { toasts: [] }

function dispatch(action: ActionType) {
  switch (action.type) {
    case actionTypes.ADD_TOAST:
      memoryState = {
        ...memoryState,
        toasts: [action.toast, ...memoryState.toasts].slice(0, TOAST_LIMIT),
      }
      break

    case actionTypes.UPDATE_TOAST:
      memoryState = {
        ...memoryState,
        toasts: memoryState.toasts.map((t) =>
          t.id === action.toast.id ? { ...t, ...action.toast } : t
        ),
      }
      break

    case actionTypes.DISMISS_TOAST:
      memoryState = {
        ...memoryState,
        toasts: memoryState.toasts.filter((t) =>
          action.toastId ? t.id !== action.toastId : false
        ),
      }
      break

    case actionTypes.REMOVE_TOAST:
      memoryState = {
        ...memoryState,
        toasts: memoryState.toasts.filter((t) =>
          action.toastId ? t.id !== action.toastId : false
        ),
      }
      break
  }

  listeners.forEach((listener) => {
    listener(memoryState)
  })
}

export function toast(props: Omit<Toast, "id">) {
  const id = genId()

  dispatch({
    type: actionTypes.ADD_TOAST,
    toast: { ...props, id },
  })

  setTimeout(() => {
    dispatch({ type: actionTypes.REMOVE_TOAST, toastId: id })
  }, TOAST_REMOVE_DELAY)

  return {
    id,
    dismiss: () => dispatch({ type: actionTypes.REMOVE_TOAST, toastId: id }),
  }
}

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

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

  return {
    ...state,
    toast,
    dismiss: (toastId?: string) =>
      dispatch({ type: actionTypes.DISMISS_TOAST, toastId }),
  }
}