import { toast } from 'react-toastify';
import { WidgetError } from 'utils';

import type { ToastOptions } from 'react-toastify';

const defaultOptions: ToastOptions = {
	autoClose: 2500,
};

export const toastHandler = (_options: ToastHandlerOptions) => {
	const { error, options = defaultOptions } = _options || {};

	if (error) {
		let message: string =
			typeof error === 'string' ? error : 'Unknown error';

		if (error instanceof WidgetError) {
			console.log('instanceof WidgetError');
			message = error?.message ?? error?.errorDescription ?? message;
		} else if (error instanceof Error) {
			console.log('instanceof Error');
			message = error?.message ?? message;
		}

		console.error(error);

		return toast.error(message, {
			...options,
			autoClose: message?.length > 25 ? 5000 : undefined,
		});
	}
};

interface ToastHandlerOptions {
	error?: WidgetError | Error | string | unknown;
	options?: ToastOptions;
}
