import ArrowForwardOutlinedIcon from "@mui/icons-material/ArrowForwardOutlined";
import { Alert, Button } from "@mui/material";
import React, { useEffect, useState } from "react";

import OTPInput from "otp-input-react";

import ContentWrapper from "../../../components/ContentWrapper/ContentWrapper";
import Header from "../../../components/Header/Header";
import CartSummaryCard from "../components/CartSummaryCard/CartSummaryCard";

import { useDispatch, useSelector } from "react-redux";
import { toast } from "react-toastify";
import {
	postVerificationSteps,
	sendOTPViaEmail,
	userVerificationSuccess,
	verifyEmailOTP,
} from "../../../redux/authSlice";
import { updatePurchase } from "../../../redux/purchaseSlice";
import CheckOutProgress from "../components/CheckOutProgress/CheckOutProgress";
import style from "./UserVerification.module.css";

function UserVerificationPage() {
	const dispatch = useDispatch();

	const { purchaseDetails, userDetails, isUserVerified } = useSelector(
		({ purchase, auth }) => {
			return {
				purchaseDetails: purchase.purchaseDetails,
				userDetails: purchase.userDetails,
				isUserVerified: auth.isUserVerified,
			};
		}
	);

	const [otp, setOtp] = useState("");
	const [isLoading, setIsLoading] = useState(false);

	useEffect(() => {
		if (isUserVerified === true) return;

		const timeoutId = setTimeout(() => {
			dispatch(sendOTPViaEmail());
		}, 500);

		return () => clearTimeout(timeoutId);
	}, [isUserVerified]);

	useEffect(() => {
		if (otp.length == 6) initiateVerification();
	}, [otp]);

	const initiateVerification = async () => {
		if (isUserVerified) return;

		await dispatch(verifyEmailOTP({ otp }))
			.unwrap()
			.catch((err) => {
				toast.error("Invalid OTP");
			});

		dispatch(userVerificationSuccess());

		const payload = await dispatch(postVerificationSteps()).unwrap();

		await dispatch(updatePurchase(payload))
			.unwrap()
			.catch((err) => {
				toast.error(err.message);
			});

		setIsLoading(false);
	};

	const navigateToNextPage = () => {
		window.location.href = "/purchase/payment";
	};

	return (
		<div className={style.main_container}>
			<ContentWrapper>
				<Header theme="DARK2" />
				<div className={style.main_content}>
					<div className={style.col1}>
						<div className={style.section1}>
							<CheckOutProgress step={isUserVerified ? 3 : 2} />
						</div>

						<div className={style.section2}>
							<p>Verify Email ID</p>
							{isUserVerified ? (
								<div style={{ flexDirection: "row" }}>
									<Alert variant="filled" severity="success">
										User Verification successfull
									</Alert>
								</div>
							) : (
								<>
									<p>
										An email was sent to <span>{userDetails.email}</span>
									</p>

									<div>
										<p>Enter OTP</p>{" "}
										<OTPInput
											className={style.otp_input}
											value={otp}
											onChange={setOtp}
											autoFocus
											OTPLength={6}
											disabled={false}
											// secure
										/>
										<p>
											Did not receive the OTP? <span>Resend OTP</span>
										</p>
									</div>
								</>
							)}

							<div>
								<Button
									fullWidth
									variant="contained"
									disabled={isLoading || !isUserVerified}
									onClick={navigateToNextPage}
								>
									Next: Select Payment{" "}
									<ArrowForwardOutlinedIcon
										sx={{ marginLeft: "0.5rem", fontSize: 20 }}
									/>
								</Button>
							</div>
						</div>
					</div>{" "}
					<div className={style.col2}>
						<CartSummaryCard />
					</div>
				</div>
			</ContentWrapper>
		</div>
	);
}

export default UserVerificationPage;
