import { Box, Button, Typography } from "@mui/material";
import { makeStyles } from "@mui/styles";
import { unwrapResult } from "@reduxjs/toolkit";
import React from "react";
import { useDispatch, useSelector } from "react-redux";
import { toast } from "react-toastify";
import validator from "validator";
import BuzzInput from "../../../components/BuzzInput/BuzzInput";
import { buzzOneSignUpAsync } from "../../../redux/authSlice";
import { palette } from "../../../theme/palette";

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,
	},
}));

const SignUpScreen = () => {
	const dispatch = useDispatch();
	const { availability } = useSelector(({ auth }) => {
		return {
			availability: auth.availability,
		};
	});

	const [name, setName] = React.useState("");
	const [email, setEmail] = React.useState("");
	const [phoneNumber, setPhoneNumber] = React.useState("");
	const [password, setPassword] = React.useState("");
	const [formFilled, setFormFilled] = React.useState(false);

	const classes = useStyles();
	const navigate = useNavigate();

	React.useEffect(() => {
		if (formFilled)
			if (
				validator.isEmpty(name) &&
				validator.isEmpty(email) &&
				validator.isEmpty(phoneNumber) &&
				validator.isEmpty(password)
			) {
				setFormFilled(false);
				toast.warning("All fields are mandatory.");
			}
	}, [name, email, phoneNumber, password]);

	const checkForValidity = () => {
		// TODO ONBOARDING /v1/auth/identity/email-and-password/signup
		// if its success then call otp /v1/auth/identity/otp/send
		// if its not success then show error message

		dispatch(
			buzzOneSignUpAsync({
				name: name,
				email: email,
				contact: phoneNumber,
				password: password,
			})
		)
			.then(unwrapResult)
			.then((result) => {
				console.log("result", result);
				if (result.id && result.token) {
					navigate("/verify_otp");
				} else {
					// WarningToast(result.message);
					toast.warning(result.message);
					// WarningToast(result.validation.body.message);
				}
			});
	};

	const activateButton = () => {
		if (
			!validator.isEmpty(name) &&
			!validator.isEmpty(email) &&
			!validator.isEmpty(phoneNumber) &&
			!validator.isEmpty(password)
		) {
			setFormFilled(true);
		}
	};

	return (
		<Box
			display="flex"
			style={{ width: "100vw", height: "100vh", background: "white" }}
		>
			<Box width={"50vw"} height={"100vh"}>
				<Box px={12} mt={5}>
					<Typography variant="h3" className={classes.greyText}>
						Signup
					</Typography>
					<Typography fontSize="medium" className={classes.greyText}>
						Already have an account?{" "}
						<a style={{ cursor: "pointer" }} href="/signin" color="primary">
							SignIn
						</a>
					</Typography>
					<Box
						width={420}
						height={600}
						display="flex"
						flexDirection="column"
						justifyContent="space-between"
						className={classes.verticalSpace}
					>
						<BuzzInput
							validation={validator.isAlpha(String(name).replace(" ", ""))}
							onChange={(e) => {
								setName(e.target.value);
								activateButton();
							}}
							value={name}
							label="Your name"
							placeholder="Enter Full Name"
							required
						/>
						<BuzzInput
							validation={validator.isEmail(email)}
							onChange={(e) => {
								setEmail(e.target.value);
								activateButton();
							}}
							value={email}
							autoComplete="off"
							type="email"
							label="Work email id"
							placeholder="Eg. jondoe@workemail.com"
							required
							helperText={
								availability &&
								availability.email && (
									<Typography
										style={{
											color: palette.palette.primary.main,
											fontSize: "0.8rem",
										}}
									>
										{`Either we already know the email or it is'nt a valid one`}
									</Typography>
								)
							}
						/>
						<BuzzInput
							validation={
								validator.isMobilePhone(phoneNumber) &&
								validator.isLength(phoneNumber, 10)
							}
							onChange={(e) => {
								setPhoneNumber(e.target.value);
								activateButton();
							}}
							nationalCode
							maxLength={10}
							type="number"
							value={phoneNumber}
							label="Contact Number"
							required
							helperText={
								availability &&
								availability.contact && (
									<Typography
										style={{
											color: palette.palette.primary.main,
											fontSize: "0.8rem",
										}}
									>
										{`Either we already know the phone number or it is'nt a valid
                    one`}
									</Typography>
								)
							}
						/>
						<BuzzInput
							passwordValidation={validator.isStrongPassword(password)}
							onChange={(e) => {
								setPassword(e.target.value);
								activateButton();
							}}
							value={password}
							autoComplete="new-password"
							type="password"
							label="Create Password"
							placeholder="Eg. Johndoe@123"
							required
							helperText={
								validator.isStrongPassword(password) &&
								validator.isLength(password, 10) ? (
									<Typography
										style={{
											color: palette.palette.buzzSuccess,
											fontSize: "0.8rem",
										}}
									>
										Excellent password. Now remember it :P
									</Typography>
								) : (
									validator.isLength(password, 1) && (
										<Typography
											style={{
												color: palette.palette.primary.main,
												fontSize: "10px",
												textAlign: "right",
											}}
										>
											Password must be at least 10 characters.
										</Typography>
									)
								)
							}
						/>

						<Box className={classes.verticalSpace}>
							<Button
								style={{
									width: 420,
									height: 50,
									backgroundColor: palette.palette.primary.main,
									color: "white",
									fontSize: 10,
								}}
								disabled={!formFilled}
								color="primary"
								onClick={checkForValidity}
							>
								Create account
							</Button>
							{/* <Typography className={`${classes.greyText} ${classes.smallText}`}>
								By creating an account you agree to the{" "}
								<Box
									sx={{ cursor: "pointer" }}
									onClick={() => history.push("/terms-and-condition")}
									color={palette.palette.primary.main}
								>
									terms and conditions
								</Box>
							</Typography> */}
						</Box>
					</Box>
				</Box>
			</Box>
			<Box
				display="flex"
				justifyContent={"center"}
				alignItems={"center"}
				width="50vw"
				height="100vh"
				sx={{
					background:
						"transparent linear-gradient(326deg, #441514 0%, #441514 0%, #7553E8 100%, #441514 100%) 0% 0% no-repeat padding-box",
				}}
			>
				{/* <Carousel>

				</Carousel> */}
			</Box>
		</Box>
	);
};

export default SignUpScreen;
