"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, ForgotRecoverPasswordFormValues, ForgotRecoverPasswordTouchFields, ForgotRecoverPasswordValidationSchema } 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';
import { useSearchParams } from "next/navigation";

type SignInProps = {
  role: number; 
};

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

  const searchParams = useSearchParams();
  const token = searchParams.get("pass_recover_token");

   const handleResetPassword = async (values: ForgotRecoverPasswordFormValues) => {
    const errors = await formik.validateForm();
    formik.setTouched(ForgotRecoverPasswordTouchFields);

    if (Object.keys(errors).length === 0) {
      try {
        const response =
          await AuthenticationService.AdminAppRecoverForgotPassword({
            identify: values.identify,
            identify_confirm: values.identify_confirm,
            pass_recover_token: token as string,
            un_pe_pm: values.un_pe_pm,
        });

        const message = response?.AppRecoverForgotPassword?.snapshot?.message;

        if (message) {
          handleSignIn(values);
        } else {
          toast.error("Failed to reset password.", {
              position: "bottom-left",
              autoClose: 5000,
          });
        }
      } catch (error:any) {
        toast.error(error, {
            position: "bottom-left",
            autoClose: 5000,
        });
      }
    }
  };

  const formik = useFormik<ForgotRecoverPasswordFormValues>({
    initialValues: {
      un_pe_pm: "",
      identify: "",
      identify_confirm: "",
    },
    validationSchema: ForgotRecoverPasswordValidationSchema,
    onSubmit: handleResetPassword,
  });

  useEffect(() => {
    if (!token) {
      toast.error("Missing reset token.");
      router.push("/login/admin");
    }
  }, [token]);

  useEffect(() => {
    if (!cookies.lr_ap_tk && !cookies.lr_ap_refresh_tk) {
      generateJWT(setCookie as any);
    } 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);
    }
  });

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

  const handleSignIn = async (values: any) => {
    try{
      const data = {
        ar_id: role,
        keep_logged: "YES",
        identify: values.identify,
        un_pe_pm: values.un_pe_pm,
        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,
      });
    }
    }
  }; 

  
  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",
                  }}
                >
                  Reset Password 
                </Typography>
              </Box>

              <Box component="form" onSubmit={formik.handleSubmit}>
                {/* Email */}
                <Box mb="15px">
                  <FormControl fullWidth sx={{ mb: 2 }}>
                    <TextField
                      label="Email or UserName"
                      variant="outlined"
                      id="un_pe_pm"
                      name="un_pe_pm"
                      fullWidth
                      onChange={formik.handleChange}
                      onBlur={formik.handleBlur}
                      value={formik.values.un_pe_pm}
                      error={
                        formik.touched.un_pe_pm &&
                        Boolean(formik.errors.un_pe_pm)
                      }
                      helperText={
                        formik.touched.un_pe_pm &&
                        formik.errors.un_pe_pm
                      }
                    />
                  </FormControl>
                </Box>

                {/* New Password */}
                <Box mb="15px">
                  <FormControl fullWidth sx={{ mb: 2 }}>
                    <TextField
                      label="New Password"
                      type="password"
                      variant="outlined"
                      id="identify"
                      name="identify"
                      fullWidth
                      onChange={formik.handleChange}
                      onBlur={formik.handleBlur}
                      value={formik.values.identify}
                      error={
                        formik.touched.identify &&
                        Boolean(formik.errors.identify)
                      }
                      helperText={
                        formik.touched.identify &&
                        formik.errors.identify
                      }
                    />
                  </FormControl>
                </Box>

                {/* Confirm Password */}
                <Box mb="15px">
                  <FormControl fullWidth sx={{ mb: 2 }}>
                    <TextField
                      label="Confirm Password"
                      type="password"
                      variant="outlined"
                      id="identify_confirm"
                      name="identify_confirm"
                      fullWidth
                      onChange={formik.handleChange}
                      onBlur={formik.handleBlur}
                      value={formik.values.identify_confirm}
                      error={
                        formik.touched.identify_confirm &&
                        Boolean(formik.errors.identify_confirm)
                      }
                      helperText={
                        formik.touched.identify_confirm &&
                        formik.errors.identify_confirm
                      }
                    />
                  </FormControl>
                </Box>

                {/* Submit Button */}
                <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>
                    Reset Password
                  </Button>
                </Box>

              </Box>
            </Box>
          </Box>
        </Box>
      </Box>
      <ToastContainer/>
    </>
  );
};

export default ForgotRecoverPassword;
