"use client"; import React, { createContext, useContext, useState, useCallback } from "react"; import { Toast, ToastTitle, ToastDescription, ToastClose } from "./toast"; import { CheckCircle, AlertCircle, AlertTriangle, Info, X } from "lucide-react"; interface ToastMessage { id: string; type: "success" | "error" | "warning" | "info"; title: string; description?: string; duration?: number; } interface ToastContextType { showToast: (message: Omit) => void; showSuccess: (title: string, description?: string) => void; showError: (title: string, description?: string) => void; showWarning: (title: string, description?: string) => void; showInfo: (title: string, description?: string) => void; } const ToastContext = createContext(undefined); export const useToast = () => { const context = useContext(ToastContext); if (!context) { throw new Error("useToast must be used within a ToastProvider"); } return context; }; interface ToastProviderProps { children: React.ReactNode; } export const ToastProvider: React.FC = ({ children }) => { const [toasts, setToasts] = useState([]); const removeToast = useCallback((id: string) => { setToasts((prev) => prev.filter((toast) => toast.id !== id)); }, []); const showToast = useCallback((message: Omit) => { const id = Math.random().toString(36).substr(2, 9); const newToast: ToastMessage = { ...message, id, duration: message.duration || 5000, }; setToasts((prev) => [...prev, newToast]); // Auto remove toast after duration setTimeout(() => { removeToast(id); }, newToast.duration); }, [removeToast]); const showSuccess = useCallback((title: string, description?: string) => { showToast({ type: "success", title, description }); }, [showToast]); const showError = useCallback((title: string, description?: string) => { showToast({ type: "error", title, description }); }, [showToast]); const showWarning = useCallback((title: string, description?: string) => { showToast({ type: "warning", title, description }); }, [showToast]); const showInfo = useCallback((title: string, description?: string) => { showToast({ type: "info", title, description }); }, [showToast]); const getToastVariant = (type: ToastMessage["type"]) => { switch (type) { case "success": return "success"; case "error": return "destructive"; case "warning": return "warning"; case "info": return "info"; default: return "default"; } }; const getToastIcon = (type: ToastMessage["type"]) => { switch (type) { case "success": return ; case "error": return ; case "warning": return ; case "info": return ; default: return null; } }; return ( {children} {/* Toast Container */}
{toasts.map((toast) => (
{getToastIcon(toast.type)}
{toast.title} {toast.description && ( {toast.description} )}
removeToast(toast.id)} />
))}
); };