import * as React from "react";
import {
	Box,
	Button,
	Checkbox,
	FormControlLabel,
	FormLabel,
	FormControl,
	TextField,
	Typography,
	Grid,
	IconButton,
	Link,
} 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 { toast } from "sonner";
import { useNavigate } from "react-router-dom";
import { Visibility, VisibilityOff } from "@mui/icons-material";
import { Card, SignInContainer } from "./styled.css.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 },
	} = useForm<ILoginForm>();
	const dispatch = useDispatch();
	const router = useNavigate();

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

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

	const onSubmit: SubmitHandler<ILoginForm> = async (data: ILoginForm) => {
		try {
			const response = await dispatch(loginUser(data)).unwrap();
			if (response?.data?.token) {
				router("/panel/dashboard");
			}
		} catch (error: any) {
			console.log("Login failed:", error);
			toast.error("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: "0%", 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}
						sx={{
							backgroundColor: "black",
							display: "flex",
							justifyContent: "center",
							alignItems: "center",
							flexDirection: "column",
							padding: { xs: "2rem", md: "3rem", lg: "3rem" },
							height: "100%",
						}}
					>
						<Typography
							variant="h3"
							sx={{
								color: "white",
								textAlign: "center",
								fontSize: {
									xs: "2rem",
									sm: "2.2rem",
									md: "36px",
								},
							}}
						>
							Welcome Back!
						</Typography>

						<Card
							variant="outlined"
							sx={{
								maxWidth: "400px",
								width: { xs: "80%", sm: "80%", md: "100%" },
							}}
						>
							<Box
								component="form"
								onSubmit={handleSubmit(onSubmit)}
								noValidate
								sx={{
									display: "flex",
									flexDirection: "column",
									gap: 2,
								}}
							>
								<Typography
									component="h1"
									variant="h4"
									sx={{
										textAlign: "center",
										color: "white",
										fontSize: { xs: "1.5rem", sm: "2rem" },
									}}
								>
									Login
								</Typography>
								<Typography
									component="h6"
									variant="subtitle2"
									sx={{
										textAlign: "center",
										color: "white",
										fontSize: { xs: "0.9rem", sm: "1rem" },
									}}
								>
									Log in with your email and password
								</Typography>

								<FormControl sx={{ width: "100%" }}>
									<FormLabel
										htmlFor="email"
										sx={{
											fontSize: {
												xs: "0.9rem",
												sm: "1rem",
											},
											color: "white",
										}}
									>
										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"
												}
												sx={{
													input: {
														fontSize: {
															xs: "0.9rem",
															sm: "1rem",
														},
													},
												}}
											/>
										)}
									/>
								</FormControl>

								<FormControl sx={{ width: "100%" }}>
									<FormLabel
										htmlFor="password"
										sx={{
											fontSize: {
												xs: "0.9rem",
												sm: "1rem",
											},
											color: "white",
										}}
									>
										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.",
											},
										}}
										render={({ field }) => (
											<Box sx={{ position: "relative" }}>
												<TextField
													{...field}
													error={!!errors.password}
													helperText={
														errors.password?.message
													}
													name="password"
													placeholder="Password"
													type={
														showPassword
															? "text"
															: "password"
													}
													id="password"
													autoComplete="current-password"
													autoFocus
													required
													fullWidth
													variant="outlined"
													color={
														errors.password
															? "error"
															: "primary"
													}
												/>
												<IconButton
													sx={{
														position: "absolute",
														top: "50%",
														right: "10px",
														background: "none",
														borderColor:
															"transparent",
														transform:
															"translateY(-50%)",
														"&:hover": {
															backgroundColor:
																"transparent",
															borderColor:
																"transparent",
														},
													}}
													onClick={() =>
														setShowPassword(
															(prev) => !prev
														)
													}
												>
													{showPassword ? (
														<VisibilityOff />
													) : (
														<Visibility />
													)}
												</IconButton>
											</Box>
										)}
									/>
								</FormControl>

								<Box
									sx={{
										display: "flex",
										justifyContent: "space-between",
										color: "white",
									}}
								>
									<FormControlLabel
										control={
											<Checkbox
												value="remember"
												color="primary"
											/>
										}
										label="Remember me"
									/>
									<Link
										component="button"
										type="button"
										onClick={handleClickOpen}
										variant="body2"
										sx={{
											alignSelf: "center",
											color: "#01579b",
										}}
									>
										Forgot password?
									</Link>
								</Box>
								<ForgotPassword
									open={open}
									handleClose={handleClose}
								/>
								<Button
									type="submit"
									fullWidth
									sx={{
										color: "white",
										backgroundColor: "#52ACDF",
										"&:hover": {
											backgroundColor: "#52ACDF",
											opacity: 0.9,
										},
									}}
								>
									Login
								</Button>
							</Box>
						</Card>
					</Grid>
				</Grid>
			</SignInContainer>
		</AppTheme>
	);
}
