import React, { createContext, useContext, useState, ReactNode, useCallback, useRef } from 'react'; interface AlertConfig { type: 'success' | 'error' | 'warning' | 'info'; title: string; message: string; } interface ConfirmConfig { title: string; message: string; } interface AlertContextType { showAlert: (config: AlertConfig) => void; showConfirm: (config: ConfirmConfig) => Promise; } const AlertContext = createContext(undefined); export const useAlert = () => { const context = useContext(AlertContext); if (!context) { throw new Error('useAlert must be used within AlertProvider'); } return context; }; interface AlertProviderProps { children: ReactNode; } export const AlertProvider: React.FC = ({ children }) => { const [alertConfig, setAlertConfig] = useState<(AlertConfig & { isOpen: boolean }) | null>(null); const [confirmConfig, setConfirmConfig] = useState<(ConfirmConfig & { isOpen: boolean }) | null>(null); const confirmResolveRef = useRef<((value: boolean) => void) | null>(null); const showAlert = (config: AlertConfig) => { setAlertConfig({ ...config, isOpen: true }); }; const closeAlert = () => { setAlertConfig(null); }; const showConfirm = useCallback((config: ConfirmConfig): Promise => { return new Promise((resolve) => { confirmResolveRef.current = resolve; setConfirmConfig({ ...config, isOpen: true }); }); }, []); const handleConfirm = (result: boolean) => { setConfirmConfig(null); if (confirmResolveRef.current) { confirmResolveRef.current(result); confirmResolveRef.current = null; } }; return ( {children} {/* Alert Dialog */} {alertConfig && (
{/* Backdrop */}
{/* Dialog */}
{/* Icon and Title */}
{getIcon(alertConfig.type)}

{alertConfig.title}

{/* Message */}

{alertConfig.message}

{/* Button */}
)} {/* Confirm Dialog */} {confirmConfig && (
{/* Backdrop */}
handleConfirm(false)} /> {/* Dialog */}
{/* Icon and Title */}

{confirmConfig.title}

{/* Message */}

{confirmConfig.message}

{/* Buttons */}
)} ); }; const getIcon = (type: 'success' | 'error' | 'warning' | 'info') => { const icons = { success: ( ), error: ( ), warning: ( ), info: ( ), }; return icons[type]; }; const getBorderColor = (type: 'success' | 'error' | 'warning' | 'info') => { const colors = { success: 'border-green-500', error: 'border-red-500', warning: 'border-amber-500', info: 'border-blue-500', }; return colors[type]; };