import { useConfig } from "@hooks/useConfig";
import {
	type ReactElement,
	type ReactNode,
	createContext,
	useContext,
	useState,
} from "react";

export type ToastType = "success" | "error" | "info" | "warning";
export type Toast = {
	id: number;
	title: string;
	message: string | ReactElement;
	type: ToastType;
};
type ShowToast = (
	title: string,
	message: string | ReactElement,
	type?: ToastType,
) => void;

const ToastContext = createContext<
	{ toasts: Toast[]; showToast: ShowToast } | undefined
>(undefined);

export const ToastProvider = ({ children }: { children: ReactNode }) => {
	const [toasts, setToasts] = useState<Toast[]>([]);

	const showToast = (
		title: string,
		message: string | ReactElement,
		type: ToastType = "success",
	) => {
		const id = Date.now();
		setToasts((prevToasts) => [...prevToasts, { id, title, message, type }]);

		// Automatically remove the toast after a certain timeout
		setTimeout(() => {
			setToasts((prevToasts) => prevToasts.filter((toast) => toast.id !== id));
		}, 3000);
	};

	return (
		<ToastContext.Provider value={{ toasts, showToast }}>
			{children}
		</ToastContext.Provider>
	);
};

export const useToast = () => {
	const context = useContext(ToastContext);
	const bungeeConfig = useConfig();

	if (!context) {
		throw new Error("useToast must be used within a ToastProvider");
	}

	if (!bungeeConfig?.features?.internalToasts) {
		return {
			toasts: [],
			showToast: () => {}, // no-op function when toasts are disabled
		};
	}
	return context;
};
