import ArrowForwardOutlinedIcon from "@mui/icons-material/ArrowForwardOutlined";
import { Button, FormControl, InputLabel, TextField } from "@mui/material";
import { useFormik } from "formik";
import React, { useEffect } from "react";

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

import { useDispatch, useSelector } from "react-redux";
import BuzzMultiSelect from "../../BuzzMultiSelect/BuzzMultiSelect";
import BuzzSelect from "../../BuzzSelect/BuzzSelect";
import { findUserByEmail, setUser, setUserProfile } from "../../redux/authSlice";
import { getAllTeenybeansLanguages, saveUserDetails, updatePurchase } from "../../redux/purchaseSlice";
import { capitalize, months } from "../../utils";
import CheckOutProgress from "../components/CheckOutProgress/CheckOutProgress";
import style from "./UserDetails.module.css";
import { store } from "../../redux/store";
import { Provider } from "react-redux";

function UserDetailsPage() {
	const dispatch = useDispatch();
	// const navigate = useNavigate();

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

	const productDetails = useFormik({
		initialValues: {
			teenybeansLanguages: [],
			teenybeansSessionStartMonth: "",
		},
		validate: (values) => {
			const errors = {};
			if (values.teenybeansLanguages.length === 0) {
				errors.teenybeansLanguages = "Required";
			}
			if (!values.teenybeansSessionStartMonth) {
				errors.teenybeansSessionStartMonth = "Required";
			}

			return errors;
		},
		onSubmit: (values) => {},
		enableReinitialize: true,
	});

	const formik = useFormik({
		initialValues: {
			email: "",
			fullName: "",
			address: "",
			city: "",
			pincode: "",
		},
		validate: (values) => {
			const errors = {};
			if (!values.fullName) {
				errors.fullName = "Required";
			}

			if (!values.email) {
				errors.email = "Required";
			} else if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(values.email)) {
				errors.email = "Invalid email address";
			}

			if (!values.address) {
				errors.address = "Required";
			}

			if (!values.city) {
				errors.city = "Required";
			}

			if (!values.pincode) {
				errors.pincode = "Required";
			}

			return errors;
		},
		onSubmit: async (values) => {
			let cartItems = purchaseDetails.cartItems.filter(({ plan }) =>
				plan.products.includes("TEENYBEANS")
			);

			cartItems = JSON.parse(JSON.stringify(cartItems));

			for (let cartItem of cartItems) {
				if (productDetails.values.teenybeansLanguages)
					cartItem.teenybeansLanguages = productDetails.values.teenybeansLanguages;

				if (productDetails.values.teenybeansSessionStartMonth)
					cartItem.teenybeansSessionStartMonth =
						productDetails.values.teenybeansSessionStartMonth;

				dispatch(
					updatePurchase({
						cartItem,
					})
				);
			}

			dispatch(saveUserDetails(values));
			// navigate("/purchase/user_verification");
			window.location.href = "/purchase/user_verification";
		},
		enableReinitialize: true,
	});

	useEffect(() => {
		if (userDetails) {
			formik.setValues(userDetails);
		}
	}, [userDetails]);

	useEffect(() => {
		if (!purchaseDetails || !purchaseDetails.cartItems) return;

		const teenybeansProduct = purchaseDetails.cartItems.filter(({ plan }) =>
			plan.products.includes("TEENYBEANS")
		)[0];

		if (!teenybeansProduct) return;

		const { teenybeansLanguages, teenybeansSessionStartMonth } =
			teenybeansProduct;

		productDetails.setValues({
			teenybeansLanguages: teenybeansLanguages || [],
			teenybeansSessionStartMonth: teenybeansSessionStartMonth || "",
		});
	}, [purchaseDetails]);

	useEffect(() => {
		dispatch(getAllTeenybeansLanguages());
	}, []);

	useEffect(() => {
		if (!formik.values.email) return;

		const timeoutId = setTimeout(async () => {
			const user = await dispatch(findUserByEmail({ email: formik.values.email }))
				.unwrap()
				.catch(() => {
					// formik.setFieldValue("userId", "");
					// formik.setFieldValue("schoolId", "");
					dispatch(setUser(null));
					dispatch(setUserProfile(null));
				});

			if (!user) {
				dispatch(setUser(user));
				return;
			}

			formik.setFieldValue("fullName", user.name);

			user.adminProfiles = user.profiles.filter(
				({ role }) => role === "SCHOOL_ADMIN" || role === "EDUCATOR_ADMIN"
			);

			if (user.adminProfiles.length === 1)
				dispatch(setUserProfile(user.adminProfiles[0]));

			dispatch(setUser(user));
		}, 500);

		return () => clearTimeout(timeoutId);
	}, [formik.values.email]);

	return (
		<Provider store={store}>
		<div className={style.main_container}>
			<ContentWrapper>
				<Header theme="DARK2" />
				<div className={style.main_content}>
					<div className={style.col1}>
						<div className={style.section1}>
							<CheckOutProgress step={formik.isValid ? 2 : 1} />
						</div>

						{/* {adminProfiles.length > 0 && (
							<Alert severity="info">We have found your aKadmy profile.</Alert>
						)} */}

						<form onSubmit={formik.handleSubmit}>
							<FormControl sx={{ width: "100%" }}>
								<div className={style.section2}>
									<p>Contact Information</p>
									<div>
										{" "}
										<InputLabel htmlFor="email" required={true}>
											Email ID
										</InputLabel>
										<TextField
											fullWidth
											id="email"
											{...formik.getFieldProps("email")}
											error={formik.touched.email && formik.errors.email}
											helperText={formik.errors.email ? formik.errors.email : " "}
											placeholder="Enter registered email id"
											required={true}
											// disabled={user && user.email}
										/>
									</div>
									<div>
										{" "}
										<InputLabel htmlFor="fullName" required={true}>
											Your Full Name
										</InputLabel>
										<TextField
											fullWidth
											id="fullName"
											{...formik.getFieldProps("fullName")}
											error={formik.touched.fullName && formik.errors.fullName}
											helperText={formik.errors.fullName ? formik.errors.fullName : " "}
											placeholder="Enter here"
											required={true}
											// disabled={user && user.name}
										/>
									</div>

									{user && user.adminProfiles.length > 0 && (
										<div>
											<InputLabel
												htmlFor="schoolId"
												required={true}
												style={{ marginBottom: "10px" }}
											>
												Select School
											</InputLabel>

											<BuzzSelect
												size="small"
												width={"100%"}
												name="schoolId"
												menuList={user.adminProfiles.map((profile) => {
													return { label: profile.school?.name, value: profile._id };
												})}
												value={userProfile?._id}
												onChange={(e) =>
													dispatch(
														setUserProfile(
															user.adminProfiles.find(({ _id }) => _id === e.target.value)
														)
													)
												}
											/>
										</div>
									)}
								</div>

								<div className={style.section3}>
									<p>Billing Information</p>
									<div>
										{" "}
										<InputLabel htmlFor="address" required={true}>
											Address
										</InputLabel>
										<TextField
											fullWidth
											id="address"
											{...formik.getFieldProps("address")}
											error={formik.touched.address && formik.errors.address}
											helperText={formik.errors.address ? formik.errors.address : " "}
											required={true}
										/>
									</div>
									<div className={style.row}>
										<div>
											{" "}
											<InputLabel htmlFor="city" required={true}>
												City
											</InputLabel>
											<TextField
												fullWidth
												id="city"
												{...formik.getFieldProps("city")}
												error={formik.touched.city && formik.errors.city}
												helperText={formik.errors.city ? formik.errors.city : " "}
												required={true}
											/>
										</div>
										<div>
											{" "}
											<InputLabel htmlFor="pincode" required={true}>
												Pin Code
											</InputLabel>
											<TextField
												fullWidth
												id="pincode"
												{...formik.getFieldProps("pincode")}
												error={formik.touched.pincode && formik.errors.pincode}
												helperText={formik.errors.pincode ? formik.errors.pincode : " "}
												required={true}
											/>
										</div>
									</div>
								</div>

								{purchaseDetails &&
									purchaseDetails.cartItems &&
									purchaseDetails.cartItems.filter(({ plan }) =>
										plan.products.includes("TEENYBEANS")
									).length > 0 && (
										<div className={style.section3}>
											<p>Teenybeans Product Information</p>

											<div className={style.row} style={{ marginBottom: "2rem" }}>
												<div style={{ width: "50%" }}>
													<InputLabel
														htmlFor="teenybeansLanguages"
														// required={true}
														sx={{ marginBottom: "10px" }}
													>
														Languages
													</InputLabel>
													<BuzzMultiSelect
														id="teenybeansLanguages"
														value={productDetails.values.teenybeansLanguages}
														menuList={teenybeansLanguages.map(({ name, _id }) => {
															return { label: name, value: _id };
														})}
														onChange={(e) =>
															productDetails.setFieldValue(
																"teenybeansLanguages",
																e.target.value
															)
														}
														required={true}
													/>
												</div>
												<div style={{ width: "50%" }}>
													{" "}
													<InputLabel
														htmlFor="teenybeansSessionStartMonth"
														// required={true}
														sx={{ marginBottom: "10px" }}
													>
														Session Start Month
													</InputLabel>
													<BuzzSelect
														id="teenybeansSessionStartMonth"
														value={productDetails.values.teenybeansSessionStartMonth}
														menuList={months.map((value) => {
															return { label: capitalize(value.toLowerCase()), value };
														})}
														onChange={(e) =>
															productDetails.setFieldValue(
																"teenybeansSessionStartMonth",
																e.target.value
															)
														}
														required={true}
													/>
												</div>
											</div>
										</div>
									)}

								<Button
									fullWidth
									sx={{ marginBottom: "100px", marginTop: "20px" }}
									variant="contained"
									type="submit"
									disabled={!formik.isValid}
								>
									Next: Verification{" "}
									<ArrowForwardOutlinedIcon
										sx={{ marginLeft: "0.5rem", fontSize: 20 }}
									/>
								</Button>
							</FormControl>
						</form>
					</div>{" "}
					<div className={style.col2}>
						<CartSummaryCard />
					</div>
				</div>
			</ContentWrapper>
		</div>
		</Provider>
	);
}

export default UserDetailsPage;
