import { useEffect, useState } from 'react';
import Stack from '@mui/material/Stack';

import { useLoginWithPassword, useSendMagicLink, useWidget } from 'hooks';
import {
	EmailInput,
	LoadingButton,
	// LoginButton,
	PasswordInput,
} from 'components';

import type { ButtonProps, OutlinedTextFieldProps } from '@mui/material';

export interface EmailFormProps
	extends Omit<OutlinedTextFieldProps, 'onSubmit' | 'onClick' | 'variant'> {
	onClick?: ButtonProps['onClick'];
	value?: string;
}

const EmailForm = (props: EmailFormProps) => {
	const { children, value = '', onClick } = props;

	const { flow = 'email', loginHint } = useWidget();
	const { mutate: sendMagicLink, isLoading: isLoadingEmail } =
		useSendMagicLink();
	const { mutate: login, isLoading: isLoadingPassword } =
		useLoginWithPassword();

	const isPassword = flow.includes('password') || false;

	const [emailValue, setEmailValue] = useState<string>(value);
	const [passwordValue, setPasswordValue] = useState<string>('');
	const [errorTextEmail, setErrorTextEmail] = useState<string | undefined>();
	const [errorTextPassword, setErrorTextPassword] = useState<
		string | undefined
	>();
	const [isErrorEmail, setIsErrorEmail] = useState<boolean>(false);
	const [isErrorPassword, setIsErrorPassword] = useState<boolean>(false);

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

		if (isMounted && (!emailValue || emailValue === '') && loginHint) {
			setEmailValue(loginHint);
		}

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

	const validateEmailInput = (allowBlank: boolean = false) => {
		if ((!emailValue || emailValue === '') && !allowBlank) {
			setErrorTextEmail('Please enter your email');
			setIsErrorEmail(() => true);
			return false;
		} else {
			setErrorTextEmail('');
			setIsErrorEmail(() => false);
			return true;
		}
	};

	const validatePasswordInput = (allowBlank: boolean = false) => {
		if ((!passwordValue || passwordValue === '') && !allowBlank) {
			setErrorTextPassword('Please enter a valid password');
			setIsErrorPassword(true);
			return false;
		} else {
			setErrorTextPassword('');
			setIsErrorPassword(false);
			return true;
		}
	};

	const handleEmailInputChange: React.ChangeEventHandler<
		HTMLInputElement
	> = ({ target }) => {
		const { value } = target;

		if (value || value === '') {
			validateEmailInput();
			setEmailValue(value);
		}
	};

	const handlePasswordInputChange: React.ChangeEventHandler<
		HTMLInputElement
	> = ({ target }) => {
		const { value } = target;

		if (value || value === '') {
			validatePasswordInput();
			setPasswordValue(value);
		}
	};

	const onKeyDown: React.KeyboardEventHandler<HTMLDivElement> = ({ key }) => {
		if (key === 'Enter') {
			handleSubmit();
		}
	};

	const handleSubmit = () => {
		if (validateEmailInput()) {
			if (!isPassword && !isErrorEmail) {
				return sendMagicLink({ email: emailValue });
			}

			if (isPassword && validatePasswordInput()) {
				if (!isErrorPassword && !isErrorEmail) {
					login({ email: emailValue, password: passwordValue });
				}
			}
		}
	};

	return (
		<>
			<Stack sx={{ width: '100%' }}>
				<EmailInput
					value={emailValue}
					onChange={handleEmailInputChange}
					disabled={isLoadingEmail}
					ButtonProps={{ onClick }}
					onBlur={() => validateEmailInput(true)}
					{...{
						helperText: errorTextEmail,
						error: !!errorTextEmail,
						onKeyDown,
					}}
				/>
				{isPassword && (
					<PasswordInput
						id='password'
						helperText={errorTextPassword}
						error={isErrorPassword}
						onBlur={() => validatePasswordInput(true)}
						onChange={handlePasswordInputChange}
						disabled={isLoadingPassword}
						value={passwordValue}
						{...{ onKeyDown }}
					/>
				)}
			</Stack>
			<Stack spacing={2} sx={{ width: '100%' }}>
				<LoadingButton
					disabled={isLoadingEmail || isLoadingPassword}
					loading={isLoadingEmail || isLoadingPassword}
					onClick={() => handleSubmit()}
				>
					Continue
				</LoadingButton>
				{/* {!isPassword && (
					<LoginButton
						variant='password'
						onClick={() => goTo('password')}
					/>
				)} */}
				{children}
			</Stack>
		</>
	);
};

export default EmailForm;
