import React from 'react';
import Toast from 'components/Toast';
import { ToasterDispatch, ToasterProps } from 'types';
import { ToastProvider, useToaster } from './context';

const removeToast = (id: string, dispatch: ToasterDispatch) =>
	dispatch({ id, type: 'remove' });

function ToasterContainer() {
	const {
		dispatch,
		state: { toasts },
	} = useToaster();
	return (
		<>
			{toasts.map(toast => {
				const close = () => removeToast(toast.id, dispatch);
				return <Toast {...toast} close={close} key={toast.id} />;
			})}
		</>
	);
}

function Toaster({ children, ...props }: ToasterProps) {
	return (
		<ToastProvider {...props}>
			{children}
			<ToasterContainer />
		</ToastProvider>
	);
}

export { Toaster, useToaster };
