'use client'
/* The LoginForm component allows users to log in to their account. */
import React, { useEffect } from "react";
import styles from "./LoginForm.module.scss";
import ImagesConstants from "@/src/utils/ImagesConstants";
import Routes from "@/src/utils/RouteConstants";
import Link from "next/link";
import { useForm } from "react-hook-form";
import { z } from 'zod';
import { zodResolver } from '@hookform/resolvers/zod'
import { LoginFormData } from "../AuthTypes/AuthTypes";
import { AUTH_COOKIES, COMMON_VARS, REGEX } from "@/src/utils/commonVariables";
import { useRouter } from "next/navigation";
import { signInThunk } from "@/redux/thunks/Auth/authentication.thunk";
import { useDispatch } from "react-redux";
import { AppDispatch } from "@/redux/store";
import { setEncryptedCookie, getEncryptedCookie, deleteCookie } from '@/src/utils/commonFunctions';
import Image from "next/image";

const LoginForm: React.FC<{ LoginContent: any }> = ({ LoginContent }) => {

    const router = useRouter();
    const dispatch = useDispatch<AppDispatch>();

    /**
   * Schema for validating user sign-up form data using Zod.
   * This schema ensures all required fields are filled with valid data
   * and enforces specific validation rules for each input.
   */
    const LoginSchema = z.object({
        /**
         * Email - Required and must match the defined email pattern.
         */
        email: z
            .string()
            .min(1, { message: LoginContent.FORM.EMAIL_REQUIRED }) // Required field
            .regex(REGEX.EMAIL, { message: LoginContent.FORM.EMAIL_INVALID }), // Must follow email pattern

        /**
         * Password - Required, must have a minimum of 8 characters.
         */
        password: z
            .string()
            .min(1, { message: LoginContent.FORM.PASSWORD_REQUIRED }) // Required field
            .min(8, { message: LoginContent.FORM.PASSWORD_MIN_LENGTH }) // Minimum 8 characters
            .trim(), // Removes leading/trailing spaces

        /**
       * RememberMe - Optional
       */
        rememberMe: z.boolean()
    });

    /**
       * Initializes the useForm hook for managing form state and validation.
       *
       * @typedef {LoginFormData} - The expected data structure for the login form.
       */
    const {
        handleSubmit,
        formState: { errors },
        register,
        reset,
        setFocus
    } = useForm<LoginFormData>({
        /**
         * Resolver integrates Zod schema validation into React Hook Form.
         * Ensures validation logic defined in `LoginSchema` is applied.
         */
        //@ts-ignore
        resolver: zodResolver(LoginSchema),
        /**
        * Default form values.
        */
        defaultValues: {
            rememberMe: false
        }
    });


    /**
   * Handles the login process by preparing the payload and dispatching the login action.
   * @param formValues The user-provided login form data.
   */
    const handleLogin = async (formValues: any) => {

        const payload = {
            email: formValues.email,
            password: formValues.password,
            userType: COMMON_VARS.USER_TYPE.GUEST
        }


        /* Dispatch the login action with the payload and a callback function */
        dispatch(
            signInThunk(payload, (data) => {
                /* If login is successful, handle cookie storage and navigation */
                if (data?.meta?.status) {
                    /* If user is verified redirect to the home otherwise redirect to OTP verification screen upon successful login */
                    if (data?.meta?.isVerified) {
                    } else {
                        router.push(`${Routes.OTP_VERIFICATION}?email=${data?.data?.email}`);
                    }
                }
            })
        );
    };
    return (
        <>
            {/* Title Section */}
            <div className={`${styles.TitleWrapper}`}>
                <h2>{LoginContent.LOGIN}</h2>
                <p className="fs-14">{LoginContent.WELCOME_BACK}</p>
            </div>
            {/* Title Section end*/}

            {/* Login section */}
            <div className="LoginMain">
                <form onSubmit={handleSubmit(handleLogin)} className={`${styles.LoginForm}`}>
                    {/* Email input wrapper */}
                    <div className="InputWrapper">
                        <label htmlFor="email">{LoginContent.EMAIL}</label>
                        <input
                            type="email"
                            id="email"
                            placeholder={LoginContent.FORM.ENTER_EMAIL}
                            {...register('email')}
                        />
                        {/* error message text */}
                        {errors.email && (
                            <p className="error-msg">
                                {errors.email?.message}
                            </p>
                        )}
                    </div>
                    {/* Email input wrapper end*/}
                    {/* Password wrapper */}
                    <div className="InputWrapper">
                        <label htmlFor="password">{LoginContent.PASSWORD}</label>
                        <input
                            type="password"
                            id="password"
                            placeholder="Enter your Password"
                            {...register('password')}
                        />
                        {/* error message text */}
                        {errors.password && (
                            <p className="error-msg">
                                {errors.password?.message}
                            </p>
                        )}
                    </div>
                    {/* Password wrapper end*/}

                    {/* Forget password */}
                    <div className={`${styles.ForgetPassword} flex justify-between items-center`}>
                        <div className={`${styles.RememberCheckbox} flex gap-1`}>
                            <label className="fs-14" htmlFor="remember">
                                <input type="checkbox" id="remember" {...register('rememberMe')} />
                                <span >{LoginContent.FORM.REMEMBER_FOR_30_DAYS}</span>
                            </label>
                        </div>
                        <p className="fs-14">
                            <Link href={Routes.FORGOT_PASSWORD}>{LoginContent.FORGOT_PASSWORD}</Link>
                        </p>
                    </div>
                    {/* Forget password end */}
                    <button className="primaryBtn" type="submit">{LoginContent.LOGIN}</button>
                </form>
                <div className={`${styles.ThirdPartyLogin} grid grid-cols-3 gap-3 mt-4`}>
                    <a href="#" className={`${styles.ThirdPartyBox} flex justify-center items-center h-[44px] w-full`}>
                        <Image className={`w-[24px] h-[24px]`} src={ImagesConstants.GOOGLE} alt="login-apps" />
                    </a>
                    <a href="#" className={`${styles.ThirdPartyBox} flex justify-center items-center h-[44px] w-full`}>
                        <Image className={`w-[24px] h-[24px]`} src={ImagesConstants.FACEBOOK} alt="login-apps" />
                    </a>
                    <a href="#" className={`${styles.ThirdPartyBox} flex justify-center items-center h-[44px] w-full`}>
                        <Image className={`w-[24px] h-[24px]`} src={ImagesConstants.APPLE} alt="login-apps" />
                    </a>
                </div>
            </div>
            {/* Login section end */}

            {/* Already have account */}
            <div className={`AuthAlreadyBox`}>
                <p className="fs-14">
                    {LoginContent.DONT_HAVE_ACCOUNT} <Link href={Routes.REGISTER}>{LoginContent.SIGN_UP}</Link>
                </p>
            </div>
            {/* Already have account end */}
        </>
    );
};

export default LoginForm;
