import { Box, Button, styled, Typography } from "@mui/material";
import { unwrapResult } from "@reduxjs/toolkit";
import OTPInput from "otp-input-react";
import * as React from "react";
import { useDispatch, useSelector } from "react-redux";
import { toast } from "react-toastify";
import { buzzOneGetUserAsync, buzzOneSignInAsync, buzzOneVerifyOtpAsync, emailResendOtpAsync } from "../redux/authSlice";
import { palette } from "../theme/palette";
import { TOKEN_NAME } from "../utils/constants";

const ButtonCustom = styled(Button)(({ theme }) => ({
	"& .MuiButton-label": {
		fontSize: "12px",
	},
}));

const OTPFieldCustom = styled(OTPInput)(({ theme }) => ({
	"& input": {
		background: theme.palette.buzzGreyBlue,
		border: "none",
		height: "55px !important",
		width: "40px !important",
	},
}));

// const useStyles = makeStyles((theme) => ({
// 	greyText: {
// 		color: theme.palette.buzzGreyColor,
// 	},
// 	smallText: {
// 		...theme.typography.body2,
// 	},
// 	verticalSpace: {
// 		margin: "50px 0",
// 	},
// 	button: {
// 		backgroundColor: theme.palette.primary.main,
// 		color: theme.palette.buzzContainerColor,
// 		// height: 40,
// 	},
// 	otpInputs: {
// 		"& input": {
// 			background: theme.palette.buzzGreyBlue,
// 			border: "none",
// 			height: "55px !important",
// 			width: "40px !important",
// 		},
// 	},
// }));

const MailVerificationLink = ({
	onPhaseChange,
	dataSet,
	showFromPublicRoute = false,
}) => {
	// const navigate = useNavigate();
	const classes = useStyles();

	const dispatch = useDispatch();

	const [OTP, setOTP] = React.useState("");
	const [message, setMessage] = React.useState(
		"NOTE: Cannot resend otp before 60 seconds."
	);

	const { user } = useSelector(({ signInReducer }) => {
		return {
			user: signInReducer.user,
		};
	});

	const skipAndProceed = async () => {
		if (showFromPublicRoute) {
			// navigate("/school-account");
			window.location.href = "/school-account";
		} else {
			let email = dataSet.email;
			let password = dataSet.password;
			dispatch(buzzOneSignInAsync({ email, password }))
				.then(unwrapResult)
				.then(async (res) => {
					if (res.status === 200) {
						await localStorage.setItem(TOKEN_NAME, res.token);
						await localStorage.setItem("userId", res.data.userId);
						dispatch(buzzOneGetUserAsync())
							.then(unwrapResult)
							.then(() => {
								// navigate("/school-account");
								window.location.href = "/school-account";
							});
					}
				});
		}
	};

	const resendOtp = async () => {
		try {
			const data = await dispatch(
				emailResendOtpAsync({
					token: localStorage.getItem(TOKEN_NAME) || dataSet.token,
				})
			);

			// console.log(data);
			data.payload && setMessage(data.payload.message);
		} catch (error) {
			setMessage(error.message);
		}
	};

	const verifyOtp = async () => {
		dispatch(
			buzzOneVerifyOtpAsync({
				otp: OTP,
				token: localStorage.getItem(TOKEN_NAME) || dataSet.token,
			})
		)
			.then(unwrapResult)
			// .then((res) => res.status === 200 && skipAndProceed());
			.then((res) => {
				toast.success(res.message);
				// navigate("/school-account");
				window.location.href = "/school-account";
			})
			.catch((res) => {
				toast.error(res.message);
			});
	};

	return (
		<>
			<Typography variant="h4">Thanks, check your inbox</Typography>
			<Box my={2} />
			<Typography style={{ fontSize: "12px", color: palette.palette.buzzFade }}>
				We’ve sent an email to{" "}
				<span style={{ color: palette.palette.primary.main }}>
					{user && user.email ? user.email : dataSet && dataSet.email}
				</span>{" "}
				with a verification link.
			</Typography>
			<Box my={2} />
			<Typography style={{ fontSize: "12px", color: palette.palette.buzzFade }}>
				If it’s been a few minutes and you still haven’t received anything, check
				your spam folder or{" "}
				<span
					style={{ color: palette.palette.primary.main, cursor: "pointer" }}
					onClick={resendOtp}
				>
					resend the email
				</span>
				.
			</Typography>

			<Box my={3} />
			<OTPFieldCustom
				value={OTP}
				onChange={setOTP}
				autoFocus
				OTPLength={6}
				disabled={false}
				// secure
				className={classes.otpInputs}
			/>

			<Box my={3} />
			<ButtonCustom
				variant="contained"
				color="primary"
				fullWidth
				onClick={verifyOtp}
			>
				Verify otp
			</ButtonCustom>

			<Box my={3} />
			<ButtonCustom
				variant="outlined"
				color="primary"
				fullWidth
				onClick={skipAndProceed}
			>
				Skip for now
			</ButtonCustom>

			<Box my={3} />
			<Typography
				style={{ fontSize: "12px", color: palette.palette.primary.main }}
			>
				{message}
			</Typography>
		</>
	);
};

export default MailVerificationLink;
