"use client";
import React from "react";
import styles from "./loginPage.module.scss";
import Box from "@mui/material/Box";
import Typography from "@mui/material/Typography";
import Grid from "@mui/material/Grid";
import { UTILITY_CONSTANT } from "@/utilities/utilityConstant";
import Link from "next/link";
import CustomizedInputsStyled from "@/ui/CustomizedInputsStyled";
import CustomizedButtons from "@/ui/customizedButtons";
import { useForm } from "react-hook-form";
import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import { useState } from "react";
import { loginApi } from "@/services/api/loginApi";
import { FormControl } from "@mui/material";
import CustomTextField from "@/ui/CustomTextField";
import { useRouter } from "next/navigation";
import { useDispatch, useSelector } from "react-redux";
import { RootState } from "@/services/store";
import { setAuthTokens, setUserDetails } from "@/services/store/authSlice";
import { routes } from "constant/route.constant";
import { grey } from "@mui/material/colors";

const loginSchema = z.object({
  username: z.string(),
  password: z.string(),
});

type LoginFormValues = z.infer<typeof loginSchema>;

export default function LoginPage() {
  const [loader, setLoader] = useState(false);
  const router = useRouter();
  const {
    register,
    handleSubmit,
    formState: { errors },
    control,
  } = useForm<LoginFormValues>({
    resolver: zodResolver(loginSchema),
  });
  const [error, setError] = useState("");
  const dispatch = useDispatch();
  const onSubmit = async (data: LoginFormValues) => {
    try {
      setLoader(true);
      const response = await loginApi(data);
      localStorage.setItem("token", response.token);
      localStorage.setItem("refreshToken", response.refreshToken);
      dispatch(
        setAuthTokens({
          token: response.token,
          refreshToken: response.refreshToken,
        })
      );
      dispatch(setUserDetails(response));
      setLoader(false);
      router.push(routes.PRODUCTS);
    } catch (err) {
      setLoader(false);
      setError("Invalid credentials");
    }
  };

  return (
    <main className={styles.loginPage}>
      <Grid container sx={{ height: "100%" }}>
        <Grid item display={{ xs: "none", md: "block" }} md={7}>
          <Box
            height={"100%"}
            sx={{
              background: grey[900],
              overflow: "hidden",
              height: "100vh",
            }}
            display={"flex"}
            alignItems={"center"}
            justifyContent={"space-between"}
          >
            <img
              src={UTILITY_CONSTANT.IMAGES.AUTH.LOGIN_BG}
              alt=""
              className={styles.images}
            />
          </Box>
        </Grid>
        <Grid item xs={12} md={5}>
          <Box
            width={"100%"}
            height={"100%"}
            display={"flex"}
            flexDirection={"column"}
            justifyContent={"space-between"}
            alignItems={"flex-start"}
            gap={4}
            paddingInline={5}
            paddingBlock={5}
          >
            <img src={UTILITY_CONSTANT.IMAGES.AUTH.HEADER_LOG} alt="logo" />
            <form onSubmit={handleSubmit(onSubmit)} style={{ width: "100%" }}>
              <Typography variant="h4" color={"var(--primary_text_clr)"}>
                Welcome to Convexsol
              </Typography>
              <Typography variant="h4" color={"var(--primary_text_clr)"}>
                Sign in to your account
              </Typography>
              <Box
                width={"100%"}
                marginBlockStart={"40px"}
                display={"flex"}
                alignItems={"flex-start"}
                flexDirection={"column"}
                gap={3}
              >
                <CustomTextField
                  name="username"
                  control={control}
                  label="Username"
                  error={!!errors.username}
                  helperText={errors.username?.message}
                />
                <CustomTextField
                  name="password"
                  control={control}
                  label="Password"
                  type="password"
                  error={!!errors.password}
                  helperText={errors.password?.message}
                />
              </Box>
              <Box width={"100%"} marginBlockStart={"20px"}>
                <CustomizedButtons
                  btnType="submit"
                  label={!loader ? "Login" : "Login..."}
                />
              </Box>
            </form>
            <Box
              width={"100%"}
              display={"flex"}
              alignItems={"center"}
              justifyContent={"space-between"}
              flexWrap={"wrap"}
              gap={2}
            >
              <Typography variant="caption" color={"var(--primary_text_clr)"}>
                © 2024 ConvexSol. Pvt.Ltd. All rights reserved.
              </Typography>
              <Typography variant="caption">
                <Link href={"#"} color={"var(--primary_text_clr)"}>
                  Privacy Policy
                </Link>{" "}
                |{" "}
                <Link href={"#"} color={"var(--primary_text_clr)"}>
                  Terms of Use
                </Link>
              </Typography>
            </Box>
          </Box>
        </Grid>
      </Grid>
    </main>
  );
}
