import * as React from "react";
import {
	Box,
	Button,
	Checkbox,
	FormControlLabel,
	FormLabel,
	FormControl,
	TextField,
	Typography,
	Grid,

	Link,
	InputAdornment,
} from "@mui/material";
import { useForm, Controller, SubmitHandler } from "react-hook-form";
import { useDispatch } from "react-redux";
import { loginUser } from "../../../redux/slices/authSlice.ts";
import AppTheme from "../../../shared-theme/AppTheme.tsx";
import ForgotPassword from "./ForgotPassword.tsx";
import { useNavigate } from "react-router-dom";
import { Visibility, VisibilityOff } from "@mui/icons-material";
import { Card, SignInContainer } from "./styled.css.tsx";
import { CustomIconButton } from "../../../components/AddUserModal/styled.css.tsx";
import { AppDispatch } from "../../../redux/store/store.ts";
interface ILoginForm {
	email: string;
	password: string;
}

export default function Login(props: { disableCustomTheme?: boolean }) {
	const [open, setOpen] = React.useState(false);
	const [showPassword, setShowPassword] = React.useState(false);

	const {
		control,
		handleSubmit,
		formState: { errors, isValid },trigger
	} = useForm<ILoginForm>({ mode: "onChange" });
	const dispatch = useDispatch<AppDispatch>();
	const router = useNavigate();

	const handleClickOpen = () => {
		setOpen(true);
	};

	const handleClose = () => {
		setOpen(false);
	};
    
   const togglePasswordVisibility = (e: React.MouseEvent) => {
      e.preventDefault(); // Prevent focus loss
      setShowPassword((prev) => !prev);
   };
  
	const onSubmit: SubmitHandler<ILoginForm> = async (data: ILoginForm) => {
		const isValid = await trigger(); // This triggers validation for all fields
    if (!isValid) {
        return; // Stop submission if there are errors
    }
		try {
			const response = await dispatch(loginUser(data)).unwrap();
			if (response?.data?.token) {
				router("/panel/dashboard");
			}
		} catch (error: any) {
			console.log("Login failed:", error);
		}
	};

	return (
		<AppTheme {...props}>
			<SignInContainer direction="column" justifyContent="space-between">
				<Grid container sx={{ height: "100vh" }}>
					{/* Image Section */}
					<Grid
						item
						xs={0}
						sm={0}
						md={7}
						sx={{
							background: `url('/mainPageLogo.png') center/cover no-repeat`,
							// height: { xs: "0%", sm: "50%", md: "100%" },
							backgroundSize: "cover",
							display: { xs: "none", md: "block" }, // Hide the image on xs and sm screens
						}}
					/>

					{/* Form Section */}
					<Grid
						item
						xs={12}
						md={5}
						width="408px"
						height="498px"
						sx={{
							backgroundColor: "black",
							display: "flex",
							justifyContent: "center",
							alignItems: "center",
							flexDirection: "column",
							padding: { xs: "2rem", md: "3rem", lg: "3rem" },
							height: "auto",
						}}
					>
						<Box
							sx={{
								textAlign: "center",
								marginBottom: "1rem",
							}}
						>
							<img
								src="/evLogo.png"
								alt="Logo"
								style={{
									justifyContent: "center",
									width: "180px",
									height: "auto",
								}}
							/>
						</Box>
						<Typography
							variant="h3"
							width={"408px"}
							height={"46px"}
							sx={{
								color: "white",
								textAlign: "center",
								fontSize: {
									xs: "2rem",
									sm: "2.2rem",
									md: "36px",
								},
							}}
						>
							Welcome Back!
						</Typography>

						<Card
							variant="outlined"
							sx={{
								width: { xs: "100%", sm: "300px", lg: "408px" },
								height:{lg:"428px"},
								padding: "24px",
								borderRadius: "9px",
								border: "1px solidrgb(45, 48, 49)",
								"*:where([data-mui-color-scheme='dark']) &": {
									backgroundColor: "#1E1E1E",
								},
							}}
						>
							<Box
								component="form"
								onSubmit={handleSubmit(onSubmit)}
								noValidate
								sx={{
									display: "flex",
									flexDirection: "column",
									gap: 2,
								}}
							>
								<Typography
									component="h1"
									variant="h4"
									sx={{
										textAlign: "center",
										color: "white",
										fontFamily: "Gilroy",
										fontSize: "24px",
									}}
								>
									Login
								</Typography>
								<Typography
									component="h6"
									variant="subtitle2"
									sx={{
										textAlign: "center",
										color: "white",
										fontFamily: "Gilroy",
										fontSize: "16px",
									}}
								>
									Log in with your email and password
								</Typography>

								{/* -------------------------------- Email Field ----------------- */}
								<FormControl sx={{ width: "100%" }}>
									<FormLabel
										htmlFor="email"
										sx={{
											fontSize: {
												xs: "0.9rem",
												sm: "1rem",
											},
											color: "white",
											fontFamily: "Gilroy, sans-serif",
										}}
									>
										Email
									</FormLabel>
									<Controller
										name="email"
										control={control}
										defaultValue=""
										rules={{
											required: "Email is required",
											pattern: {
												value: /\S+@\S+\.\S+/,
												message:
													"Please enter a valid email address.",
											},
										}}
										render={({ field }) => (
											<TextField
												{...field}
												error={!!errors.email}
												helperText={
													errors.email?.message
												}
												id="email"
												type="email"
												placeholder="Email"
												autoComplete="email"
												autoFocus
												required
												fullWidth
												variant="outlined"
												color={
													errors.email
														? "error"
														: "primary"
												}
												InputProps={{
													sx: {
														height: "50px",
														alignItems: "center",
														backgroundColor:
															"#1E1F1F",
														fontFamily:
															"Gilroy, sans-serif",
													},
												}}
												sx={{
													"& .MuiOutlinedInput-root":
														{
															backgroundColor:
																"#1E1F1F",
															borderRadius: "4px",
															"& fieldset": {
																borderColor:
																	"#4b5255",
															},
															"&:hover fieldset":
																{
																	borderColor:
																		"#4b5255",
																},
															"&.Mui-focused fieldset":
																{
																	borderColor:
																		"#4b5255",
																},
														},

													"& input": {
														color: "white",
														fontSize: {
															xs: "0.9rem",
															sm: "1rem",
														},
														fontFamily:
															"Gilroy, sans-serif",
													},
													"& .MuiInputBase-input::placeholder":
														{
															color: "white",
															opacity: 1,
															fontFamily:
																"Gilroy, sans-serif",
														},
												}}
											/>
										)}
									/>
								</FormControl>

								{/* -------------------------------- Password Field ----------------- */}
								<FormControl sx={{ width: "100%" }}>
									<FormLabel
										htmlFor="password"
										sx={{
											fontSize: {
												xs: "0.9rem",
												sm: "1rem",
											},
											color: "white",
											fontFamily: "Gilroy, sans-serif",
										}}
									>
										Password
									</FormLabel>
									<Controller
										name="password"
										control={control}
										defaultValue=""
										rules={{
											required: "Password is required",
											minLength: {
												value: 6,
												message:
													"Password must be at least 6 characters long.",
											},
											pattern: {
												value: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{6,}$/,
												message:
													"Password must contain at least one uppercase letter, one lowercase letter, one number, and one special character.",
											},
										}}
										render={({ field }) => (
											<TextField
												{...field}
												error={!!errors.password}
												helperText={
													errors.password?.message
												}
												name="password"
												placeholder="Password"
												type={
													showPassword
														? "text"
														: "password"
												}
												id="password"
												autoComplete="current-password"
												required
												fullWidth
												variant="outlined"
												color={
													errors.password
														? "error"
														: "primary"
												}
												InputProps={{
													endAdornment: (
														<InputAdornment position="end">
															<CustomIconButton
																aria-label="toggle password visibility"
																onClick={
																	togglePasswordVisibility
																}
																edge="end"
															>
																{showPassword ? (
																	<VisibilityOff />
																) : (
																	<Visibility />
																)}
															</CustomIconButton>
														</InputAdornment>
													),
												}}
												sx={{
													"& .MuiOutlinedInput-root":
														{
															backgroundColor:
																"#1E1F1F",
															borderRadius: "4px",
															"& fieldset": {
																borderColor:
																	"#4b5255",
															},
															"&:hover fieldset":
																{
																	borderColor:
																		"#4b5255",
																},
															"&.Mui-focused fieldset":
																{
																	borderColor:
																		"#4b5255",
																},
														},
													"& input": {
														color: "white",
														fontSize: {
															xs: "0.9rem",
															sm: "1rem",
														},
														fontFamily:
															"Gilroy, sans-serif",
													},
													"& .MuiInputBase-input::placeholder":
														{
															color: "white",
															opacity: 1,
															fontFamily:
																"Gilroy, sans-serif",
														},
												}}
											/>
										)}
									/>
								</FormControl>

								<Box
									sx={{
										display: "flex",
										justifyContent: "space-between",
										color: "white",
										alignItems: "center",
										flexWrap: "wrap",
									}}
								>
									<FormControlLabel
										control={
											<Checkbox
												value="remember"
												sx={{
													width: 20,
													height: 20,
													fontFamily:
														"Gilroy, sans-serif",
													border: "2px solid #4b5255",
													borderRadius: "4px",
													backgroundColor:
														"transparent",
													"&:hover": {
														backgroundColor:
															"transparent",
													},
													"&.Mui-checked": {
														backgroundColor:
															"transparent",
														borderColor: "#4b5255",
														"&:hover": {
															backgroundColor:
																"transparent",
														},
													},
												}}
											/>
										}
										label="Remember me"
									/>

									<Link
										component="button"
										type="button"
										onClick={handleClickOpen}
										variant="body2"
										sx={{
											alignSelf: "center",
											fontFamily: "Gilroy, sans-serif",
											color: "#01579b",
											textDecoration: "none", 
										}}
									>
										Forgot password?
									</Link>
								</Box>
								<ForgotPassword
									open={open}
									handleClose={handleClose}
								/>
								<Button
									type="submit"
									fullWidth
									disabled={!isValid}
									sx={{
										color: "white",
										fontFamily: "Gilroy, sans-serif",
										backgroundColor: "#52ACDF",
										"&:hover": {
											backgroundColor: "#52ACDF",
											opacity: 0.9,
										},
									}}
								>
									Login
								</Button>
							</Box>
						</Card>
					</Grid>
				</Grid>
			</SignInContainer>
		</AppTheme>
	);
}
