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";
import { autofillFix } from "../../../shared-theme/customizations/autoFill.tsx";

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 navigate = useNavigate();

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

	const handleClose = () => {
		setOpen(false);
	};

	const togglePasswordVisibility = (e: React.MouseEvent) => {
		e.preventDefault();
		setShowPassword((prev) => !prev);
	};

	const onSubmit: SubmitHandler<ILoginForm> = async (data: ILoginForm) => {
		const isValid = await trigger();
		if (!isValid) {
			return;
		}
		try {
			const response = await dispatch(loginUser(data)).unwrap();
			if (response?.data?.token) {
				navigate("/panel/dashboard");
			}
		} catch (error: any) {
			console.log("Login failed:", error);
		}
	};

	return (
		<AppTheme {...props}>
			<SignInContainer direction="column" justifyContent="space-between">
				<Grid container sx={{ minHeight: "100vh" }}>
					<Grid
						item
						xs={0}
						sm={0}
						md={7}
						sx={{
							background: `url('/Login.svg') center/cover no-repeat`,
							backgroundSize: "cover",
							display: { xs: "none", md: "block" },
							position: "relative",
						}}
					>
						<Box
							sx={{
								position: "absolute",
								top: "50%",
								left: "50%",
								transform: "translate(-50%, -50%)",
								display: { xs: "none", md: "block" },
							}}
						>
							<img
								src="/evLogo.png"
								alt="Logo"
								style={{
									width: "250px",
									height: "auto",
								}}
							/>
						</Box>
					</Grid>

					{/* Form Section */}
					<Grid
						item
						xs={12}
						md={5}
						sx={{
							backgroundColor: "background.default", // Use theme's default background (#DFECF1)
							display: "flex",
							justifyContent: "center",
							alignItems: "center",
							flexDirection: "column",
							padding: { xs: "1.5rem", sm: "2rem", md: "3rem" },
							position: "relative",
						}}
					>
						<Box
							sx={{
								display: { xs: "flex", md: "none" },
								justifyContent: "center",
								alignItems: "center",
								width: "100%",
								mb: 4,
							}}
						>
							<img
								src="/evLogo.png"
								alt="Logo"
								style={{
									width: "200px",
									maxWidth: "100%",
									height: "auto",
								}}
							/>
						</Box>

						<Typography
							variant="h3"
							sx={{
								color: "text.primary", // Use theme's primary text color (#000000)
								textAlign: "center",
								fontSize: {
									xs: "1.8rem",
									sm: "2.2rem",
									md: "2.5rem",
								},
								width: "100%",
								mb: { xs: 2, md: 3 },
								mt: { xs: 0, md: 0 },
								fontFamily:
									'"Publica Sans Round Medium", sans-serif',
							}}
						>
							Welcome Back!
						</Typography>

						<Card
							variant="outlined"
							sx={{
								width: {
									xs: "100%",
									sm: "90%",
									md: "90%",
									lg: "408px",
								},
								maxWidth: "408px",
								minHeight: { xs: "auto", md: "428px" },
								padding: { xs: "16px", sm: "20px", md: "24px" },
								borderRadius: "8px", // Match theme's borderRadius
								backgroundColor: "#000000", // Use theme's paper color (#D0E1E9)
								borderColor: "divider", // Use theme's divider color (#E0E0E0)
							}}
						>
							<Box
								component="form"
								onSubmit={handleSubmit(onSubmit)}
								noValidate
								sx={{
									display: "flex",
									flexDirection: "column",
									gap: { xs: 1.5, md: 2 },
								}}
							>
								<Typography
									component="h1"
									variant="h4"
									sx={{
										textAlign: "center",
										color: "#D0E1E9",
										fontSize: { xs: "20px", md: "24px" },
										fontFamily:
											'"Publica Sans Round Medium", sans-serif',
									}}
								>
									{" "}
									Login
								</Typography>
								<Typography
									component="h6"
									variant="subtitle2"
									sx={{
										textAlign: "center",
										color: "#D0E1E9", // Use theme's secondary text color (#272727)
										fontSize: { xs: "14px", md: "16px" },
										mb: 1,
										fontFamily:
											'"Publica Sans Round Medium", sans-serif',
									}}
								>
									Log in with your email and password
								</Typography>

								{/* Email Field */}
								<FormControl sx={{ width: "100%" }}>
									<FormLabel
										htmlFor="email"
										sx={{
											fontSize: {
												xs: "0.875rem",
												sm: "1rem",
											},
											color: "#D0E1E9",
											mb: 0.5,
											fontFamily:
												'"Publica Sans Round Medium", sans-serif',
											...autofillFix,
										}}
									>
										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: {
															xs: "45px",
															md: "50px",
														},
														alignItems: "center",
														backgroundColor:
															"background.paper", // Match card background
														borderRadius: "8px",
													},
												}}
												sx={{
													"& .MuiOutlinedInput-root":
														{
															"& fieldset": {
																borderColor:
																	"divider",
															},
															"&:hover fieldset":
																{
																	borderColor:
																		"text.secondary",
																},
															"&.Mui-focused fieldset":
																{
																	borderColor:
																		"primary.main",
																},
														},
													"& input": {
														color: "text.primary",
														fontSize: {
															xs: "0.875rem",
															sm: "1rem",
														},
														fontFamily:
															'"Publica Sans Round Medium", sans-serif',
													},
													"& .MuiInputBase-input::placeholder":
														{
															color: "text.secondary",
															opacity: 1,
															fontFamily:
																'"Publica Sans Round Medium", sans-serif',
														},
													...autofillFix,
												}}
											/>
										)}
									/>
								</FormControl>

								{/* Password Field */}
								<FormControl sx={{ width: "100%" }}>
									<FormLabel
										htmlFor="password"
										sx={{
											fontSize: {
												xs: "0.875rem",
												sm: "1rem",
											},
											color: "#D0E1E9",
											mb: 0.5,
											fontFamily:
												'"Publica Sans Round Medium", 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"
												autoComplete="current-password"
												type={
													showPassword
														? "text"
														: "password"
												}
												id="password"
												required
												fullWidth
												variant="outlined"
												color={
													errors.password
														? "error"
														: "primary"
												}
												InputProps={{
													sx: {
														height: {
															xs: "45px",
															md: "50px",
														},
														backgroundColor:
															"background.paper",
														borderRadius: "8px",
														...autofillFix,
													},
													endAdornment: (
														<InputAdornment position="end">
															<CustomIconButton
																aria-label="toggle password visibility"
																onClick={
																	togglePasswordVisibility
																}
																edge="end"
																sx={{color:"#000000"}}
															>
																{showPassword ? (
																	<VisibilityOff />
																) : (
																	<Visibility />
																)}
															</CustomIconButton>
														</InputAdornment>
													),
												}}
												sx={{
													"& .MuiOutlinedInput-root":
														{
															"& fieldset": {
																borderColor:
																	"divider",
															},
															"&:hover fieldset":
																{
																	borderColor:
																		"text.secondary",
																},
															"&.Mui-focused fieldset":
																{
																	borderColor:
																		"primary.main",
																},
														},
													"& input": {
														color: "text.primary",
														fontSize: {
															xs: "0.875rem",
															sm: "1rem",
														},
														fontFamily:
															'"Publica Sans Round Medium", sans-serif',
													},
													"& .MuiInputBase-input::placeholder":
														{
															color: "text.secondary",
															opacity: 1,
															fontFamily:
																'"Publica Sans Round Medium", sans-serif',
														},
												}}
											/>
										)}
									/>
								</FormControl>

								{/* Remember me and Forgot Password */}
								<Box
									sx={{
										display: "flex",
										justifyContent: "space-between",
										alignItems: "center",
										flexWrap: { xs: "wrap", sm: "nowrap" },
										gap: 1,
										mt: 1,
									}}
								>
									<FormControlLabel
										control={
											<Checkbox
												value="remember"
												sx={{
													width: { xs: 16, md: 20 },
													height: { xs: 16, md: 20 },
													border: "2px solid",
													borderColor: "divider",
													borderRadius: "4px",
													backgroundColor:
														"transparent",
													"&:hover": {
														backgroundColor:
															"transparent",
													},
													"&.Mui-checked": {
														backgroundColor:
															"transparent",
														borderColor:
															"primary.main",
														"&:hover": {
															backgroundColor:
																"transparent",
														},
													},
												}}
											/>
										}
										label={
											<Typography
												sx={{
													fontSize: {
														xs: "0.75rem",
														sm: "0.875rem",
														md: "1rem",
													},
													color: "#D0E1E9",
													fontFamily:
														'"Publica Sans Round Medium", sans-serif',
												}}
											>
												Remember me
											</Typography>
										}
									/>

									<Link
										component="button"
										type="button"
										onClick={handleClickOpen}
										variant="body2"
										sx={{
											alignSelf: "center",
											color: "#D0E1E9",
											textDecoration: "none",
											fontSize: {
												xs: "0.75rem",
												sm: "0.875rem",
												md: "1rem",
											},
											fontFamily:
												'"Publica Sans Round Medium", sans-serif',
										}}
									>
										Forgot password?
									</Link>
								</Box>

								{/* Login Button */}
								<Button
									type="submit"
									fullWidth
									disabled={!isValid}
									sx={{
										color: "#000000",
										fontWeight: 500,
										backgroundColor: "#D0E1E9",
										"&:hover": {
											backgroundColor: "#D0E1E9",
										},
										padding: { xs: "8px 0", md: "10px 0" },
										mt: { xs: 2, md: 3 },
										fontSize: {
											xs: "0.875rem",
											md: "1rem",
										},
										fontFamily:
											'"Publica Sans Round Medium", sans-serif',
									}}
								>
									Login
								</Button>
							</Box>
						</Card>
					</Grid>
				</Grid>
			</SignInContainer>
		</AppTheme>
	);
}
