import { useEffect, useState } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import Container from '@mui/material/Container';
import Paper from '@mui/material/Paper';
import Stack from '@mui/material/Stack';
import { useTheme } from '@mui/material';

import { useVerifyMagicLink, useWidget } from 'hooks';
import initFontAwesome from 'utils/initFontAwesome';
import {
	EmailVerify,
	IdentifierFirst,
	// ProgressiveCapture,
} from 'screens';
import { PageLoader, WidgetForm, WidgetHeader, WidgetTitle } from 'components';

const Widget = ({ children }: WidgetProps) => {
	const theme = useTheme();
	initFontAwesome();

	const location = useLocation();
	const navigate = useNavigate();

	const [queryParams, setQueryParams] = useState<
		URLSearchParams | undefined
	>();

	const { flow, isLoading, isLoadingAuth } = useWidget();
	const { isLoading: isLoadingVerify, mutate: verifyMagicLink } =
		useVerifyMagicLink();

	useEffect(() => {
		let isMounted = true;

		if (isMounted && location?.hash) {
			setQueryParams(new URLSearchParams(location.hash.substring(1)));
		} else if (isMounted && location?.search) {
			setQueryParams(new URLSearchParams(location.search));
		}

		return () => {
			isMounted = false;
		};
	}, [location]);

	useEffect(() => {
		let isMounted = true;

		if (
			isMounted &&
			!isLoadingVerify &&
			!isLoadingAuth &&
			!isLoading &&
			queryParams?.has('verification_code')
		) {
			navigate('/passwordless/verify_redirect', { replace: true });

			const code = queryParams.get('verification_code') || undefined;
			const redirectUri = queryParams.get('redirect_uri') || undefined;
			const email = queryParams.get('email') || undefined;
			const phone = queryParams.get('phone') || undefined;

			if (isMounted && code) {
				verifyMagicLink({ code, redirectUri, email, phone });
			}
		}

		return () => {
			if (isMounted) {
				setQueryParams(undefined);
			}
			isMounted = false;
		};
	}, [isLoadingVerify, isLoadingAuth, isLoading, queryParams]);

	const widgetContainerSx =
		theme?.mixins?.loginLayout === 'center'
			? { justifyContent: 'center', display: 'flex !important' }
			: {};

	return (
		<>
			{(isLoading || isLoadingAuth || isLoadingVerify) && <PageLoader />}
			{!(isLoading || isLoadingAuth || isLoadingVerify) && (
				<Container
					id='widget-container'
					maxWidth={false}
					sx={{ ...widgetContainerSx }}
				>
					<Paper
						id='widget'
						elevation={3}
						sx={{
							display: 'flex',
							minHeight: 600,
							py: 3,
							px: 1,
						}}
					>
						<Stack
							spacing={3}
							direction='column'
							alignItems='center'
							justifyContent='flex-start'
							sx={{ flexGrow: 1, pb: 3, width: '100%' }}
						>
							<WidgetHeader />
							<WidgetTitle />
							<WidgetForm>
								{flow === 'email-verify' ? (
									<EmailVerify />
								) : (
									<IdentifierFirst />
								)}
								{/* {flow === 'progressive' && <ProgressiveCapture />} */}
								{children}
							</WidgetForm>
						</Stack>
					</Paper>
				</Container>
			)}
		</>
	);
};

export default Widget;

export interface WidgetProps {
	children?: React.ReactNode;
}
