"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, ForgotPasswordValidationSchema, ForgotPasswordinFormValues, ForgotPasswordTouchFields } 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';

const ForgotPassword = () => {
  const [cookies, setCookie, removeCookie] = useCookies();
  const router = useRouter();
  const params = usePathname();

  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);
      }
  });
  
  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 handleForgotPassword = async (values: ForgotPasswordinFormValues) => {
    const errors = await formik.validateForm();
    formik.setTouched(ForgotPasswordTouchFields);

    if (Object.keys(errors).length === 0) {
      try {
        const response = await AuthenticationService.AdminAppForgotPasswordMutation({
          un_pe_pm: values.email,
          pass_recover_url: `${window.location.origin}/login/reset-password`
        });

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

        if (message) {
          toast.success("Password reset link sent to your email");
        } else {
          toast.error("Something went wrong");
        }

      } catch (error:any) {
        console.log(error, "error");
        if(error.includes("User email not found to send recovery link. Please Contact Administrator.")){
          toast.error(error, {
            position: "bottom-left",
            autoClose: 5000,
          });
        }
        else{
          toast.error(error, {
            position: "bottom-left",
            autoClose: 5000,
          });
        }        
      }
    }
  };

  const formik = useFormik<ForgotPasswordinFormValues>({
    initialValues: {
        email: '',
    },
    validationSchema: ForgotPasswordValidationSchema,
    onSubmit: async(values) => {
      await handleForgotPassword(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",
                  }}
                >
                  Forgot Password 
                </Typography>
              </Box>

              <Typography fontSize="14px" color="text.secondary" mb={3} > Enter your email and we’ll send you a reset link </Typography>

              <Box component="form" onSubmit={formik.handleSubmit}>
                <Box mb="15px">
                  <FormControl fullWidth sx={{ mb: 2 }}> <TextField label="Email Address or User name" variant="outlined" id="email" name="email" fullWidth onChange={formik.handleChange} onBlur={formik.handleBlur} value={formik.values.email} error={ formik.touched.email && Boolean(formik.errors.email) } helperText={ formik.touched.email && formik.errors.email } /> </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>
                    Send Reset Link
                  </Button>
                </Box>
              </Box>
            </Box>
          </Box>
        </Box>
      </Box>
      <ToastContainer/>
    </>
  );
};

export default ForgotPassword;
