import React, { createContext, useContext, useMemo, useReducer } from 'react';
import {
	ToasterAction,
	ToasterState,
	ToasterContextType,
	ToasterProps,
} from 'types';

function toastReducer(state: ToasterState, action: ToasterAction) {
	switch (action.type) {
		case 'add': {
			return {
				toasts: [...state.toasts, action.toast],
			};
		}
		case 'remove': {
			return {
				toasts: state.toasts.filter(({ id }) => id !== action.id),
			};
		}
	}
}

const initialState: ToasterState = { toasts: [] };

const ToasterContext = createContext<ToasterContextType>({
	state: initialState,
	dispatch: () => {},
});

function ToastProvider({ children }: ToasterProps) {
	const [state, dispatch] = useReducer(toastReducer, initialState);
	const value = useMemo(() => ({ state, dispatch }), [state, dispatch]);
	return (
		<ToasterContext.Provider value={value}>{children}</ToasterContext.Provider>
	);
}

const useToaster = () => useContext(ToasterContext);

export { ToastProvider, useToaster };
