"use client";
import React,{useEffect} from "react";
import {
  Button,
  Box,
  Typography,
  FormControl,
  TextField,
  Link
} from "@mui/material";
import Image from "next/image";
import { useFormik  } from 'formik';
import { SigninValidationSchema, SigninTouchFields, SigninFormValues } from '@lib/ValidationSchemas';
import { ToastContainer, toast} from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import { useCookies } from 'react-cookie';
import { v4 as uuidv4 } from 'uuid';
import { useRouter, usePathname } from 'next/navigation';
import {RoleEnum} from '@constant/StaticData';
import AuthenticationService, {AppSignOPData} from '@/service/AuthenticationService';
import {CustomCookieSetOptions, generateJWT, generateJWTusingRefTkn, checkUserToken, isTokenExpired, encodeSimpleJWT, handleFetchWithTokenRefresh} from '@utils/common';

type SignInProps = {
  role: number; 
};

const SignIn: React.FC<SignInProps> = ({ role }) => {
  const [cookies, setCookie, removeCookie] = useCookies();
  const router = useRouter();
  const params = usePathname();

  const accessCheckingAndRedirect = async (signInDatas:AppSignOPData) => {
    if( signInDatas){ 
      if (signInDatas.AppSignin?.authenticated?.uauthorisation?.ar_id === RoleEnum.ADMIN){
        router.push('/admin/floor-plan');    
      }
    }
  }

if (!cookies.lr_device_id) {
    const deviceId = uuidv4();
    const expires = new Date();
    expires.setFullYear(expires.getFullYear() + 100);
    setCookie('lr_device_id', deviceId, { path: '/', expires: expires, domain: process.env.DOMAIN});
  }
  const handleSignIn = async (values: any) => {
      const errors = await formik.validateForm();
      formik.setTouched(SigninTouchFields);  
      if (Object.keys(errors).length === 0) {
        try{
          const data = {
            ar_id: role,
            keep_logged: "YES",
            identify: values.password,
            un_pe_pm: values.email,
            device_token: cookies.lr_device_id,
          };

          const signInDatas = await AuthenticationService.AdminUserSigninMutation(data);
          if (signInDatas) {
            const keepLogged = signInDatas.AppSignin?.authenticated?.session?.keep_logged;
            let expiresdt: Date | undefined = undefined;

            if (keepLogged === 'YES') {
              const currentDT = new Date();
              expiresdt = new Date(currentDT.setFullYear(currentDT.getFullYear() + 1));
            }

            const userData = {
              username: signInDatas?.AppSignin?.username || "",
              email: signInDatas?.AppSignin?.primary_email || "",
              ar_id: RoleEnum.ADMIN ,
              user_id: signInDatas?.AppSignin?.id || 0,
            };

            setCookie('lr_u_info', encodeSimpleJWT(userData), { path: '/', expires: expiresdt, domain: process.env.DOMAIN}); 
            setCookie('lr_usr_tkn', signInDatas?.AppSignin?.authenticated?.session?.jwt, { path: '/', expires: expiresdt, domain: process.env.DOMAIN})

            accessCheckingAndRedirect(signInDatas);
        }
        }
        catch (error:any) {
          handleFetchWithTokenRefresh(error, cookies, setCookie, handleSignIn, error, values);
          if (error instanceof TypeError) {
            toast.error("Unexpected server error. please try again later.", {
              position: "bottom-left",
              autoClose: 5000,
          });
        }
      }
    }
  };  

  
   useEffect(() => {
      if(!cookies.lr_ap_tk && !cookies.lr_ap_refresh_tk){
        generateJWT(setCookie as (name: string, value: string, options?: CustomCookieSetOptions) => void);
      }
      else if(!cookies.lr_ap_tk || isTokenExpired(cookies.lr_ap_tk)){
         generateJWTusingRefTkn(cookies, setCookie);
      }
      if (cookies.lr_usr_tkn) {
         checkUserToken(RoleEnum.ADMIN, cookies, router, removeCookie, params);
      }
  });    

  const formik = useFormik<SigninFormValues>({
    initialValues: {
        email: '',
        password: '',
    },
    validationSchema: SigninValidationSchema,
    onSubmit: async(values) => {
      await handleSignIn(values);
    },
});
  return (
    <>
      <Box
        className="auth-main-wrapper sign-in-area"
        sx={{
          py: { xs: "60px", md: "80px", lg: "100px", xl: "135px" },
        }}
      >
        <Box
          sx={{
            maxWidth: { sm: "500px", md: "1255px" },
            mx: "auto !important",
            px: "12px",
          }}
        >
          <Box
            sx={{
              display: "flex",
              flexDirection: { xs: "column", md: "row" },
              alignItems: "center",
              gap: { xs: "16px", md: "32px" },
            }}
          >
            <Box
              sx={{
                flex: { md: 1 },
                display: { xs: "none", md: "block" },
              }}
            >
              <Image
                src="/Images/agency.png"
                alt="sign-in-image"
                width={425}
                height={700}
                style={{
                  borderRadius: "24px",
                }}
              />
            </Box>

            <Box
              sx={{
                flex: { md: 1 },
                paddingLeft: { xs: "0", lg: "10px" },
              }}
            >
              <Box
                className="logo"
                sx={{
                  mb: "23px",
                }}
              > 
                <Image
                  src="/Images/Logo.png"
                  alt="logo"
                  width={200}
                  height={200}
                />
              </Box>

              <Box
                className="title"
                sx={{
                  mb: "23px",
                }}
              >
                <Typography
                  variant="h1"
                  className="text-black"
                  sx={{
                    fontSize: { xs: "22px", sm: "25px", lg: "28px" },
                    mb: "7px",
                    fontWeight: "600",
                  }}
                >
                  Sign In 
                </Typography>
              </Box>

              <Box component="form" onSubmit={formik.handleSubmit}>
                <Box mb="15px">
                  <FormControl fullWidth>
                    <Typography
                      component="label"
                      sx={{
                        fontWeight: "500",
                        fontSize: "14px",
                        mb: "10px",
                        display: "block",
                      }}
                      className="text-black"
                    >
                      Username
                    </Typography>

                    <TextField
                      label="example&#64;gmail.com"
                      variant="filled"
                      id="email"
                      name="email"
                      onChange={formik.handleChange}
                      onBlur={formik.handleBlur}
                      error={formik.touched.email && Boolean(formik.errors.email)}
                      helperText={formik.touched.email && formik.errors.email}
                      sx={{
                        "& .MuiInputBase-root": {
                          border: "1px solid #D5D9E2",
                          backgroundColor: "#fff",
                          borderRadius: "7px",
                        },
                        "& .MuiInputBase-root::before": {
                          border: "none",
                        },
                        "& .MuiInputBase-root:hover::before": {
                          border: "none",
                        },
                      }}
                    />
                  </FormControl>
                </Box>

                <Box mb="15px">
                  <FormControl fullWidth>
                    <Typography
                      component="label"
                      sx={{
                        fontWeight: "500",
                        fontSize: "14px",
                        mb: "10px",
                        display: "block",
                      }}
                      className="text-black"
                    >
                      Password
                    </Typography>

                    <TextField
                      label="Type Password"
                      variant="filled"
                      type="password"
                      id="password"
                      name="password"
                      onChange={formik.handleChange}
                      onBlur={formik.handleBlur}
                      error={
                        formik.touched.password &&
                        Boolean(formik.errors.password)
                      }
                      helperText={
                        formik.touched.password && formik.errors.password
                      }
                      sx={{
                        "& .MuiInputBase-root": {
                          border: "1px solid #D5D9E2",
                          backgroundColor: "#fff",
                          borderRadius: "7px",
                        },
                        "& .MuiInputBase-root::before": {
                          border: "none",
                        },
                        "& .MuiInputBase-root:hover::before": {
                          border: "none",
                        },
                      }}
                    />
                  </FormControl>
                </Box>

                <Box mb="20px">
                  <Button
                    type="submit"
                    variant="contained"
                    sx={{
                      textTransform: "capitalize",
                      borderRadius: "6px",
                      fontWeight: "500",
                      fontSize: { xs: "13px", sm: "16px" },
                      padding: { xs: "10px 20px", sm: "10px 24px" },
                      color: "#fff !important",
                      boxShadow: "none",
                      width: "100%",
                    }}
                  >
                    <i className="material-symbols-outlined mr-5">login</i>
                    Sign In
                  </Button>
                </Box>
                
                <Box textAlign="right" mb="10px">
                  <Link
                    href="/login/forgot-password"
                    style={{ fontSize: "14px", color: "#1976d2" }}
                  >
                    Forgot Password?
                  </Link>
                </Box>
                
                <Box mb="20px">
                  <Typography>
                    
                     {/* {role === RoleEnum.ADMIN ? (
                      <Link
                        href="/login/super-admin/"
                        className="text-primary"
                        style={{
                          fontWeight: "500",
                        }}
                      >
                      Access Super Admin Login
                      </Link>
                    ) : (
                      <Link
                        href="/login/admin/"
                        className="text-primary"
                        style={{
                          fontWeight: "500",
                        }}
                      >
                     Access Admin Login
                      </Link>
                    )} */}
                    
                  </Typography>
                </Box>
              </Box>
            </Box>
          </Box>
        </Box>
      </Box>
      <ToastContainer/>
    </>
  );
};

export default SignIn;
