'use client'; import { useRef } from 'react'; import { useState, useEffect } from 'react'; import { createGlobalState } from 'react-global-hooks'; import { Dialog, DialogBackdrop, DialogPanel, DialogTitle } from '@headlessui/react'; import { FaExclamationTriangle, FaInfo } from 'react-icons/fa'; import { TextInput } from './formInputs'; import React from 'react'; import { useFromNull } from '@/hooks/useFromNull'; import classNames from 'classnames'; export interface ConfirmState { title: string; message?: string; confirmText?: string; type?: 'danger' | 'warning' | 'info'; inputTitle?: string; onConfirm?: (value?: string) => void | Promise; onCancel?: () => void; } export const confirmstate = createGlobalState(null); export const openConfirm = (confirmProps: ConfirmState) => { confirmstate.set(confirmProps); }; export default function ConfirmModal() { const [confirm, setConfirm] = confirmstate.use(); const [isOpen, setIsOpen] = useState(false); const [inputValue, setInputValue] = useState(''); const inputRef = useRef(null); useFromNull(() => { setTimeout(() => { if (inputRef.current) { inputRef.current.focus(); } }, 100); }, [confirm]); useEffect(() => { if (confirm) { setIsOpen(true); setInputValue(''); } }, [confirm]); useEffect(() => { if (!isOpen) { // use timeout to allow the dialog to close before resetting the state setTimeout(() => { setConfirm(null); }, 500); } }, [isOpen]); const onCancel = () => { if (confirm?.onCancel) { confirm.onCancel(); } setIsOpen(false); }; const onConfirm = () => { if (confirm?.onConfirm) { confirm.onConfirm(inputValue); } setIsOpen(false); }; let Icon = FaExclamationTriangle; let color = confirm?.type || 'danger'; // Use conditional rendering for icon if (color === 'info') { Icon = FaInfo; } // Color mapping for background colors const getBgColor = () => { switch (color) { case 'danger': return 'bg-red-500'; case 'warning': return 'bg-yellow-500'; case 'info': return 'bg-blue-500'; default: return 'bg-red-500'; } }; // Color mapping for text colors const getTextColor = () => { switch (color) { case 'danger': return 'text-red-950'; case 'warning': return 'text-yellow-950'; case 'info': return 'text-blue-950'; default: return 'text-red-950'; } }; // Color mapping for titles const getTitleColor = () => { switch (color) { case 'danger': return 'text-red-500'; case 'warning': return 'text-yellow-500'; case 'info': return 'text-blue-500'; default: return 'text-red-500'; } }; // Button background color mapping const getButtonBgColor = () => { switch (color) { case 'danger': return 'bg-red-700 hover:bg-red-500'; case 'warning': return 'bg-yellow-700 hover:bg-yellow-500'; case 'info': return 'bg-blue-700 hover:bg-blue-500'; default: return 'bg-red-700 hover:bg-red-500'; } }; return (
{confirm?.title}

{confirm?.message}

{ e.preventDefault() onConfirm() }}>
); }