import React, { createContext, useCallback, useContext, useMemo, useState } from "react"; import { Alert, Button, Dialog, DialogActions, DialogContent, DialogTitle, Typography } from "@mui/material"; type ConfirmOptions = { title?: string; message: string; confirmLabel?: string; cancelLabel?: string; destructive?: boolean; }; type ConfirmContextValue = { confirm: (options: ConfirmOptions) => Promise; }; type ConfirmState = ConfirmOptions & { open: boolean; resolver?: (value: boolean) => void; }; const ConfirmContext = createContext(null); export function ConfirmProvider({ children }: { children: React.ReactNode }) { const [state, setState] = useState({ open: false, message: "", title: "Confirm action", confirmLabel: "Confirm", cancelLabel: "Cancel", destructive: false, }); const closeWith = useCallback((value: boolean) => { setState((prev) => { prev.resolver?.(value); return { ...prev, open: false, resolver: undefined }; }); }, []); const confirm = useCallback((options: ConfirmOptions) => { return new Promise((resolve) => { setState({ open: true, title: options.title ?? "Confirm action", message: options.message, confirmLabel: options.confirmLabel ?? "Confirm", cancelLabel: options.cancelLabel ?? "Cancel", destructive: options.destructive ?? false, resolver: resolve, }); }); }, []); const value = useMemo(() => ({ confirm }), [confirm]); return ( {children} closeWith(false)} fullWidth maxWidth="xs"> {state.title} {state.destructive ? "This action may be hard to undo." : "Please confirm this action."} {state.message} ); } export function useConfirm() { const ctx = useContext(ConfirmContext); if (!ctx) throw new Error("useConfirm must be used within ConfirmProvider"); return ctx; }