import { Visibility, VisibilityOff } from "@mui/icons-material";
import { Box, Button, IconButton, Typography } from "@mui/material";
import { unwrapResult } from "@reduxjs/toolkit";
import { useFormik } from "formik";
import * as React from "react";
import { useDispatch } from "react-redux";
import { toast } from "react-toastify";
import validator from "validator";
import BuzzInput from "../BuzzInput/BuzzInput";
import { buzzOneGetUserAsync, buzzOneSignInAsync, logOut } from "../redux/authSlice";

const validate = (values) => {
	const errors = {};
	const { email, password } = values;

	if (!email) {
		errors.email = "**This field is required";
	} else if (!validator.isEmail(email)) {
		errors.email = "Please Enter a valid Email";
	}
	if (!password) {
		errors.password = "**This Field is required";
	} else if (password.toString().length < 5) {
		errors.password = "Password can not be less than 5 characters";
	}

	return errors;
};

const SignInPhase = ({ onPhaseChange, onDataSet }) => {
	const dispatch = useDispatch();
	// const navigate = useNavigate();

	const formik = useFormik({
		initialValues: {
			showPassword: false,
			email: "",
			password: "",
		},
		onSubmit: (values) => {
			const { email, password } = values;
			dispatch(buzzOneSignInAsync({ email, password }))
				.then(unwrapResult)
				.then((res) => {
					// console.log('all details hhh', res);
					if (!res) {
						dispatch(logOut());
						return;
					}
					onDataSet({
						email: email,
						password: password,
						token: res.token,
					});
					dispatch(buzzOneGetUserAsync())
						.then(unwrapResult)
						.then((res) => {
							// navigate("/");
							window.location.href = "/";
						});
				})
				.catch((error) => {
					toast.error(error.message);
				});
		},
		validate,
	});

	const handleShowPassword = () => {
		formik.setFieldValue("showPassword", !formik.values.showPassword);
	};

	const { email, password } = formik.values;

	return (
		<>
			<Box>
				<Typography variant="h3">Sign In</Typography>

				{/* <Box display="flex" alignItems="center">
					<Typography style={{ marginRight: 10 }}>New here ?</Typography>{" "}
					<Link underline="hover" variant="body2" to={"/signup"}>
						Create an account
					</Link>
				</Box> */}
			</Box>

			<form
				noValidate
				autoComplete="off"
				onSubmit={(e) => {
					e.preventDefault();
				}}
			>
				<Box my={5}>
					<BuzzInput
						required
						type="email"
						name="email"
						id="childNameId"
						variant="outlined"
						size="small"
						placeholder="Ex: jondoe@workemail.com"
						value={email}
						onBlur={formik.handleBlur}
						onChange={formik.handleChange}
						error={formik.touched.email && formik.errors.email !== ""}
						helperText={formik.touched.email ? formik.errors.email : ""}
					/>
				</Box>

				<Box my={5}>
					<BuzzInput
						required
						id="childNameId"
						variant="outlined"
						size="small"
						value={password}
						placeholder="Enter password"
						onChange={formik.handleChange}
						type={formik.values.showPassword ? "text" : "password"}
						name={"password"}
						onBlur={formik.handleBlur}
						error={formik.touched.password && formik.errors.password !== ""}
						helperText={formik.touched.password ? formik.errors.password : ""}
						InputProps={{
							endAdornment: (
								<IconButton
									type="checkbox"
									aria-label="toggle password visibility"
									value={formik.values.showPassword}
									onClick={handleShowPassword}
								>
									{formik.values.showPassword ? <Visibility /> : <VisibilityOff />}
								</IconButton>
							),
						}}
					/>
				</Box>
				<Button
					fullWidth
					onClick={formik.handleSubmit}
					variant="contained"
					color="primary"
				>
					Continue
				</Button>
			</form>
		</>
	);
};

export default SignInPhase;
