// Simplified version of shadcn use-toast for unblocking
import { useState, useEffect } from "react"

export interface Toast {
    id: string
    title?: string
    description?: string
    action?: React.ReactNode
    variant?: "default" | "destructive"
}

type ToastProps = Omit<Toast, "id">

let count = 0

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

type ActionType =
    | { type: "ADD_TOAST"; toast: Toast }
    | { type: "DISMISS_TOAST"; toastId?: string }
    | { type: "REMOVE_TOAST"; toastId?: string }

interface State {
    toasts: Toast[]
}

const toastTimeouts = new Map<string, ReturnType<typeof setTimeout>>()

// Simple event emitter for toast updates
const listeners: Array<(state: State) => void> = []
let memoryState: State = { toasts: [] }

function dispatch(action: ActionType) {
    switch (action.type) {
        case "ADD_TOAST":
            memoryState = { ...memoryState, toasts: [action.toast, ...memoryState.toasts].slice(0, 1) } // Limit to 1 for simplicity
            break
        case "DISMISS_TOAST":
        case "REMOVE_TOAST":
            const { toastId } = action
            if (toastId) {
                memoryState = { ...memoryState, toasts: memoryState.toasts.filter((t) => t.id !== toastId) }
            } else {
                memoryState = { ...memoryState, toasts: [] }
            }
            break
    }
    listeners.forEach((listener) => listener(memoryState))
}

function toast({ ...props }: ToastProps) {
    const id = genId()
    const update = (props: ToastProps) =>
        dispatch({ type: "ADD_TOAST", toast: { ...props, id } })
    const dismiss = () => dispatch({ type: "DISMISS_TOAST", toastId: id })

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

    return {
        id: id,
        dismiss,
        update,
    }
}

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: (toastId?: string) => dispatch({ type: "DISMISS_TOAST", toastId }),
    }
}

export { useToast, toast }
