import { deepmerge } from '@mui/utils';

const WidgetReducer: React.Reducer<
	WidgetProvider.Context,
	WidgetProvider.Action
> = (
	state: WidgetProvider.Context,
	{ type: actionType, ...newState }: WidgetProvider.Action
): WidgetProvider.Context => {
	const responder = (data?: Partial<WidgetProvider.Context>) => {
		const endState: WidgetProvider.Context = deepmerge(
			deepmerge(state, newState),
			data
		);

		const { auth0, ...rest } = endState || {};

		console.group('=== NEW STATE ===');
		console.log(`=== ${actionType} ===`);
		console.log(JSON.stringify(rest, null, 2));
		console.groupEnd();

		return endState;
	};

	switch (actionType) {
		case 'CAPTCHA_ERROR':
		case 'INITIATED_AUTH0_MANAGE':
		case 'INITIATED_OTP':
		case 'INITIATED_LOGIN_WITH_PASSWORD':
		case 'OTP_SENT':
		case 'OTP_VERIFIED':
		case 'SWITCH_FLOW':
		case 'UPDATE_OPTIONS':
		case 'USER_FETCHED':
		case 'USER_UPDATED':
			return responder();
		case 'CAPTCHA_RENDERED':
			return responder({ isInvalidCaptcha: false });
		case 'CLIENT_INITIALIZED':
			return responder({
				initialized: true,
				isLoading: false,
			});
		case 'INITIATED_CHECK_SESSION':
		case 'INITIATED_OTP_VERIFY':
		case 'INITIATED_SOCIAL_AUTH':
			return responder({ isLoadingAuth: true });
		case 'MANAGEMENT_SESSION_CHECKED':
			return responder({
				isLoading: false,
				isLoadingAuth: false,
				isAuthenticated: false,
			});
		case 'ERROR':
			return responder({ isLoading: false, isLoadingAuth: false });
		default:
			throw new Error(`Type [${actionType}] not implemented!`);
	}
};

export default WidgetReducer;
