import { BrowserRouter, useInRouterContext } from 'react-router-dom';
import { CssBaseline, ThemeProvider } from '@mui/material';
import { merge } from 'lodash';

import { Widget } from 'components';
import initFontAwesome from '../utils/initFontAwesome';

import {
	initialContext,
	WidgetProvider as WidgetStateProvider,
} from 'providers';
import { createTheme } from './theme';

import 'react-toastify/dist/ReactToastify.css';
import './style.css';

import type { PaletteColorOptions, ThemeOptions } from '@mui/material';

const Auth0Widget = ({
	authOptions: _authOptions,
	widgetTheme,
	...props
}: Auth0WidgetProps) => {
	initFontAwesome();

	const theme = createTheme(widgetTheme || {});
	const { authOptions, ...context } = initialContext;

	const WidgetApp = () => (
		<ThemeProvider {...{ theme }}>
			<CssBaseline />
			<WidgetStateProvider
				{...{
					...merge(
						{},
						context,
						{ theme: { logo: widgetTheme?.logo } },
						props
					),
					authOptions: {
						...merge(authOptions, _authOptions),
						connections:
							_authOptions?.connections ??
							authOptions.connections,
					},
				}}
			>
				<Widget />
			</WidgetStateProvider>
		</ThemeProvider>
	);

	if (!useInRouterContext()) {
		return (
			<BrowserRouter>
				<WidgetApp />
			</BrowserRouter>
		);
	}

	return <WidgetApp />;
};

export default Auth0Widget;

export interface WidgetTheme extends ThemeOptions {
	primaryColor?: PaletteColorOptions;
	secondaryColor?: PaletteColorOptions;
	auth0Theme?: Partial<Theme.Settings>;
	logo?: string;
}

export interface Auth0WidgetProps {
	authOptions: WidgetProvider.AuthOptions;
	flow?: WidgetProvider.AuthFlow;
	widgetTheme?: WidgetTheme;
}
