import * as React from "react";
import Box from "@mui/material/Box";
import Button from "@mui/material/Button";
import Checkbox from "@mui/material/Checkbox";
import CssBaseline from "@mui/material/CssBaseline";
import FormControlLabel from "@mui/material/FormControlLabel";
import Divider from "@mui/material/Divider";
import FormLabel from "@mui/material/FormLabel";
import FormControl from "@mui/material/FormControl";
import Link from "@mui/material/Link";
import TextField from "@mui/material/TextField";
import Typography from "@mui/material/Typography";
import Stack from "@mui/material/Stack";
import MuiCard from "@mui/material/Card";
import { styled } from "@mui/material/styles";
import { useForm, Controller, SubmitHandler } from "react-hook-form";
import { useDispatch } from "react-redux";
import { loginUser } from "../../../redux/slices/authSlice.ts";
import ColorModeSelect from "../../../shared-theme/ColorModeSelect.tsx";
import AppTheme from "../../../shared-theme/AppTheme.tsx";
import ForgotPassword from "./ForgotPassword.tsx";
import { toast } from "sonner";
import { useNavigate } from "react-router-dom";

const Card = styled(MuiCard)(({ theme }) => ({
	display: "flex",
	flexDirection: "column",
	alignSelf: "center",
	width: "100%",
	padding: theme.spacing(4),
	gap: theme.spacing(2),
	margin: "auto",
	[theme.breakpoints.up("sm")]: {
		maxWidth: "450px",
	},
	boxShadow:
		"hsla(220, 30%, 5%, 0.05) 0px 5px 15px 0px, hsla(220, 25%, 10%, 0.05) 0px 15px 35px -5px",
	...theme.applyStyles("dark", {
		boxShadow:
			"hsla(220, 30%, 5%, 0.5) 0px 5px 15px 0px, hsla(220, 25%, 10%, 0.08) 0px 15px 35px -5px",
	}),
}));

const SignInContainer = styled(Stack)(({ theme }) => ({
	height: "calc((1 - var(--template-frame-height, 0)) * 100dvh)",
	minHeight: "100%",
	padding: theme.spacing(2),
	[theme.breakpoints.up("sm")]: {
		padding: theme.spacing(4),
	},
	"&::before": {
		content: '""',
		display: "block",
		position: "absolute",
		zIndex: -1,
		inset: 0,
		backgroundImage:
			"radial-gradient(ellipse at 50% 50%, hsl(210, 100%, 97%), hsl(0, 0%, 100%))",
		backgroundRepeat: "no-repeat",
		...theme.applyStyles("dark", {
			backgroundImage:
				"radial-gradient(at 50% 50%, hsla(210, 100%, 16%, 0.5), hsl(220, 30%, 5%))",
		}),
	},
}));
interface ILoginForm {
	email: string;
	password: string;
}
export default function Login(props: { disableCustomTheme?: boolean }) {
	const [open, setOpen] = React.useState(false);
	const {
		control,
		handleSubmit,
		formState: { errors },
		setError,
	} = 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}>
			<CssBaseline enableColorScheme />
			<SignInContainer direction="column" justifyContent="space-between">
				<ColorModeSelect
					sx={{ position: "fixed", top: "1rem", right: "1rem" }}
				/>
				<Card variant="outlined">
					{/* <SitemarkIcon /> */}
					Digi-EV
					<Typography
						component="h1"
						variant="h4"
						sx={{
							width: "100%",
							fontSize: "clamp(2rem, 10vw, 2.15rem)",
						}}
					>
						Sign in
					</Typography>
					<Box
						component="form"
						onSubmit={handleSubmit(onSubmit)}
						noValidate
						sx={{
							display: "flex",
							flexDirection: "column",
							width: "100%",
							gap: 2,
						}}
					>
						<FormControl>
							<FormLabel htmlFor="email">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="your@email.com"
										autoComplete="email"
										autoFocus
										required
										fullWidth
										variant="outlined"
										color={
											errors.email ? "error" : "primary"
										}
									/>
								)}
							/>
						</FormControl>

						<FormControl>
							<FormLabel htmlFor="password">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 }) => (
									<TextField
										{...field}
										error={!!errors.password}
										helperText={errors.password?.message}
										name="password"
										placeholder="••••••"
										type="password"
										id="password"
										autoComplete="current-password"
										autoFocus
										required
										fullWidth
										variant="outlined"
										color={
											errors.password
												? "error"
												: "primary"
										}
									/>
								)}
							/>
						</FormControl>

						<FormControlLabel
							control={
								<Checkbox value="remember" color="primary" />
							}
							label="Remember me"
						/>
						<ForgotPassword open={open} handleClose={handleClose} />
						<Button type="submit" fullWidth variant="contained">
							Sign in
						</Button>
						<Link
							component="button"
							type="button"
							onClick={handleClickOpen}
							variant="body2"
							sx={{ alignSelf: "center" }}
						>
							Forgot your password?
						</Link>
					</Box>
					<Divider>or</Divider>
					<Box
						sx={{
							display: "flex",
							flexDirection: "column",
							gap: 2,
						}}
					>
						<Typography sx={{ textAlign: "center" }}>
							Don&apos;t have an account?{" "}
							<Link
								href="/auth/signup"
								variant="body2"
								sx={{ alignSelf: "center" }}
							>
								Sign up
							</Link>
						</Typography>
					</Box>
				</Card>
			</SignInContainer>
		</AppTheme>
	);
}
