import DangerMessage from "@/components/message/DangerMessage";
import SuccessMessage from "@/components/message/SuccessMessage";
import Modal from "@/components/modal/Modal";
import ModalBody from "@/components/modal/ModalBody";
import { useEffect, useRef, useState } from "react";
import { TimedModalProviderContext } from "../TimedModalProvider";


export function TimedModalProvider({
	children
}:{
	children: React.ReactNode;
}){
	const [ display, setDisplay ] = useState(false);
	const [ messages, setMessages ] = useState<React.ReactNode[]>([]);
	const messagesRef = useRef<React.ReactNode[]>(messages);
	messagesRef.current = messages;


	useEffect(() => {
		if(messages.length > 0){
			setDisplay(true);
		}
		else{
			setDisplay(false);
		}
	}, [ messages ]);


	const addMessage = (message: React.ReactNode, timeout: number) => {
		setMessages([...messages, message]);
		setTimeout(() => {
			setMessages(messagesRef.current.filter((m) => m !== message));
		}, timeout);
	}

	const addSuccessMessage = (message: string) => {
		addMessage(<SuccessMessage>{message}</SuccessMessage>, 5000);
	}

	const addErrorMessage = (message: string) => {
		addMessage(<DangerMessage>{message}</DangerMessage>, 5000);
	}

	const currentContext = {
		addMessage,
		addSuccessMessage,
		addErrorMessage
	}


	return (
		<TimedModalProviderContext.Provider value={currentContext}>
			<Modal
				display={display}
				backgroundType="none"
				className="bg-neutral-300 dark:bg-neutral-600 rounded-t-none"
				top={true}
			>
				<ModalBody>
					<div
						className="space-y-4"
					>
						{
							messages.map((message, index) => (
								<div
									key={index}
								>
									{message}
								</div>
							))
						}
					</div>
				</ModalBody>
			</Modal>
			{children}
		</TimedModalProviderContext.Provider>
	);
}
