import ArrowForwardOutlinedIcon from "@mui/icons-material/ArrowForwardOutlined";
import {
	Alert,
	Button,
	FormControl,
	FormControlLabel,
	Radio,
	RadioGroup,
} from "@mui/material";
import React, { useState } from "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 {
	clearPurchaseCart,
	initiatePayment,
	verifyPayment,
} from "../../../redux/purchaseSlice";
import CheckOutProgress from "../components/CheckOutProgress/CheckOutProgress";
import style from "./PaymentPage.module.css";

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

	const { purchaseDetails, userDetails } = useSelector(({ purchase }) => {
		return {
			purchaseDetails: purchase.purchaseDetails,
			userDetails: purchase.userDetails,
		};
	});
	const [step, setStep] = useState(3);
	const [phase, setPhase] = useState(0);

	const [error, setError] = useState(false);

	const initializePayment = () => {
		setStep(4);

		dispatch(initiatePayment())
			.unwrap()
			.then(async (res) => {
				console.log(res);

				setPhase(1);
				window.open(res.paymentUrl, "_blank", "rel=noopener noreferrer");

				await new Promise((resolve) => {
					setTimeout(() => {
						resolve();
					}, [4000]);
				});
				setPhase(2);

				let breakFlag = false;
				let counter = 0;
				while (counter < 200 && !breakFlag) {
					await new Promise((resolve) => {
						setTimeout(() => {
							resolve();
						}, [4000]);
					});
					counter += 1;

					dispatch(verifyPayment({ txnId: res.txnId }))
						.unwrap()
						.then((res) => {
							if (res.status === "success") {
								setPhase(3);
								dispatch(clearPurchaseCart());
								// navigate("/purchase/confirmation");
								window.location.href = "/purchase/confirmation";

								breakFlag = true;
							}
						});
				}
				if (counter >= 200) setError(true);
			})
			.catch(async () => {
				setError(true);
			});
	};
	return (
		<div className={style.main_container}>
			<ContentWrapper>
				<Header theme="DARK2" />
				{error && (
					<Alert variant="filled" severity="warning" color="error">
						Your payment could not be completed due to some error. Try Again.
					</Alert>
				)}
				<div className={style.main_content}>
					<div className={style.col1}>
						<div className={style.section1}>
							<CheckOutProgress step={step} />
						</div>

						{phase === 0 && (
							<div className={style.section2}>
								<p className={style.title}>Select a payment Method</p>

								<FormControl className={style.radio_group_container}>
									<RadioGroup
										defaultValue={purchaseDetails.currency === "INR" ? "payU" : "stripe"}
										className={style.radio_group}
									>
										<FormControlLabel
											className={style.radio_group_item}
											value="payU"
											control={<Radio />}
											label={<img src="/assets/PayU_logo.png" width={80} />}
											disabled={purchaseDetails.currency !== "INR"}
										/>
										<FormControlLabel
											className={style.radio_group_item}
											value="stripe"
											control={<Radio />}
											label={<img src="/assets/stripe_logo.png" width={80} />}
											disabled={purchaseDetails.currency !== "USD"}
										/>
										<FormControlLabel
											className={style.radio_group_item}
											value="airpay"
											control={<Radio />}
											disabled={true}
											label={
												<img
													src="/assets/airpay-text.png"
													width={80}
													style={{ opacity: 0.4 }}
												/>
											}
										/>
									</RadioGroup>
								</FormControl>
								{/* <p>PAYU</p> */}

								<div>
									<Button
										fullWidth
										variant="contained"
										disabled={false}
										onClick={initializePayment}
									>
										Payment
										<ArrowForwardOutlinedIcon
											sx={{ marginLeft: "0.5rem", fontSize: 20 }}
										/>
									</Button>
								</div>
							</div>
						)}
						{phase === 1 && (
							<Alert variant="filled" severity="info">
								Redirecting to the payment page ...
							</Alert>
						)}
						{phase === 2 && (
							<Alert variant="filled" severity="info">
								Verifying payment ...
							</Alert>
						)}
					</div>{" "}
					<div className={style.col2}>
						<CartSummaryCard />
					</div>
				</div>
			</ContentWrapper>
		</div>
	);
}

export default PaymentPage;
