"use client";
import React,{useEffect} from "react";
import { useCookies } from 'react-cookie';
import { v4 as uuidv4 } from 'uuid';
import {RoleEnum} from '@constant/StaticData';
import { useRouter, usePathname } from 'next/navigation';
import AuthenticationService, {AppSignOPData} from '@/service/AuthenticationService';
import { useFormik  } from 'formik';
import { SigninFrontValidationSchema, SigninTouchFields, SigninFormValues } from '@lib/ValidationSchemas';
import {CustomCookieSetOptions, generateJWT, generateJWTusingRefTkn, checkUserToken, isTokenExpired, encodeSimpleJWT, handleFetchWithTokenRefresh, decodeSimpleJWT} from '@utils/common';
import { ToastContainer, toast} from 'react-toastify';
import '@styles/common.css';
import '@styles/home.css';
import 'react-toastify/dist/ReactToastify.css';


const Home: React.FC = () => {
    const [cookies, setCookie, removeCookie] = useCookies();
    const router = useRouter();
    const params = usePathname();
    const decodedUserData = cookies.lr_u_info ? decodeSimpleJWT(cookies.lr_u_info) : null;
    const [isClient, setIsClient] = React.useState(false);

    useEffect(() => {
        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});
        }
    });

    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.CUSTOMER, cookies, router, removeCookie, params);
        }
    });

    useEffect(() => {
      if (cookies.lr_usr_tkn && decodedUserData && decodedUserData.ar_id === RoleEnum.CUSTOMER) {
          setIsClient(false);
      }
      else{
        setIsClient(true);
      }
  }, [decodedUserData, cookies]);

    const formik = useFormik<SigninFormValues>({
        initialValues: {
            email: '',
            password: '',
        },
        validationSchema: SigninFrontValidationSchema,
        onSubmit: async(values) => {
          await handleSignIn(values);
        },
    });

    const handleSignIn = async (values: any) => {
        const errors = await formik.validateForm();
        formik.setTouched(SigninTouchFields);  
        if (Object.keys(errors).length === 0) {
          try{
            const data = {
              ar_id: RoleEnum.CUSTOMER,
              keep_logged: "YES",
              otp: 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.CUSTOMER ,
                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})
          }
          }
          catch (error:any) {
            const message = error.replace(/OTP/g, "Password");
            handleFetchWithTokenRefresh(message, cookies, setCookie, handleSignIn, message, values);
          }
        }
    }; 
    
    return (
        <>
           <main id="home-pg">
            <section className="h-100">
                <div className="container-fluid h-100">
                    <div className="row h-100">
                        <div className="col-12  h-100">
                            <div className="d-flex justify-content-center h-100 align-items-center">
                            {isClient && (
                              <>
                                <form className="text-center" onSubmit={formik.handleSubmit}>
                                    <div className="mb-3">
                                      <input
                                          type="email"
                                          className="form-control rounded-pill inpborder"
                                          placeholder="Username or Email"
                                          aria-label="Email Address"
                                          value={formik.values.email}
                                          name="email"
                                          onChange={formik.handleChange}
                                          onBlur={formik.handleBlur}
                                      />
                                      {formik.touched.email && formik.errors.email ? (
                                          <div className="text-danger text-start">{formik.errors.email}</div>
                                      ) : null}
                                    </div>
                                    <div className="mb-3">
                                      <input
                                          type="password"
                                          className="form-control rounded-pill inpborder"
                                          placeholder="Password"
                                          aria-label="Password"
                                          value={formik.values.password}
                                          name="password"
                                          onChange={formik.handleChange}
                                          onBlur={formik.handleBlur}
                                      />
                                      {formik.touched.password && formik.errors.password ? (
                                          <div className="text-danger text-start">{formik.errors.password}</div>
                                      ) : null}
                                    </div>
                                    <button type="submit" className="btn btn-success rounded-pill">
                                        Login
                                    </button>
                                </form>
                              </>
                              )}
                            </div>
                        </div>
                    </div>
                </div>
            </section>
        </main>
        <ToastContainer/>
        </>
    );
};

export default Home;