'use client'
/*
  This component is for the login form.
  It includes a form with an email input and a password input.
  It also includes a button to login.
  It also includes a button to go back to the create profile page.
*/
import { RootState } from '@/redux/slices';
import { commonActions } from '@/redux/slices/Common/commonSlice';
import { AppDispatch } from "@/redux/store";
import { signInThunk } from '@/redux/thunks/Auth/authentication.thunk';
import { LoginFormData } from '@/src/components/Form/AuthTypes/AuthTypes';
import { LRFFlowContent } from '@/src/types/StaticContent/lrfflow.content.type';
import { COMMON_VARS } from '@/src/utils/commonVariables';
import { zodResolver } from '@hookform/resolvers/zod';
import { useRouter } from 'next/navigation';
import { useState } from 'react';
import { useForm } from "react-hook-form";
import { useDispatch, useSelector } from "react-redux";
import { z } from 'zod';

const LoginForm = ({ CreateProfileContent }: { CreateProfileContent: LRFFlowContent }) => {

    const router = useRouter();
    const dispatch = useDispatch<AppDispatch>();
    const [showPassword, setShowPassword] = useState(false);
    const { LRFData } = useSelector((state: RootState) => state.common);
    const { viewBookingData } = useSelector((state: RootState) => state.booking);
    /**
   * 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: CreateProfileContent.LOGIN.FORM.EMAIL_OR_USERNAME_REQUIRED }), // Required field
        // .regex(REGEX.EMAIL, { message: CreateProfileContent.LOGIN.FORM.EMAIL_INVALID }), // Must follow email pattern

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

    });

    /**
       * 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),
        defaultValues: {
            email: LRFData?.email ?? ''
        }
    });

    /**
   * 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: any = {
            email: formValues.email,
            password: formValues.password,
            userType: COMMON_VARS.USER_TYPE.GUEST
        }

        if (viewBookingData && viewBookingData?.data?.bookingId) {
            payload.bookingId = viewBookingData?.data?.bookingId
        }


        /* 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 user is verified redirect to the home otherwise redirect to OTP verification screen upon successful login */
                if (data?.meta?.isVerified) {
                    dispatch(commonActions.setLRFFlow(null))
                    dispatch(commonActions.setLRFModalOpen(false))
                    setTimeout(() => {
                        dispatch(commonActions.setIsLoggedIn(true));
                        router.refresh();
                    }, 100)
                } else {
                    dispatch(commonActions.setLRFFlow('otp-verification'))
                }
            })
        );
    };

    return (
        <>
            <form onSubmit={handleSubmit(handleLogin)}>
                <div className="InputWrapper">
                    <label htmlFor="email">{CreateProfileContent.LOGIN.FORM.EMAIL} or {CreateProfileContent.LOGIN.FORM.USERNAME}</label>
                    <input
                        className={`!bg-bgColor !fs-16`}
                        type="text"
                        id="email"
                        placeholder={CreateProfileContent.LOGIN.FORM.ENTER_EMAIL}
                        {...register('email')}
                    />
                    {/* error message text */}
                    {errors.email && (
                        <p className="error-msg">
                            {errors.email?.message}
                        </p>
                    )}
                </div>
                <div className="InputWrapper">
                    <label htmlFor="password">{CreateProfileContent.LOGIN.FORM.PASSWORD}</label>
                    <div className={`relative`}>
                        <input
                            className={`!bg-bgColor !fs-16`}
                            type={showPassword ? 'text' : 'password'}
                            id="password"
                            placeholder={CreateProfileContent.LOGIN.FORM.ENTER_PASSWORD}
                            {...register('password')}
                        />
                        <span onClick={() => setShowPassword(prev => !prev)} className={`absolute top-1/2 transition-transform -translate-1/2 right-3 cursor-pointer`}><i className={`!bg-grey85 !w-[18px] !h-[18px] Icon ${showPassword ? 'IconEyeClose' : 'IconEyeOpenPassword'}`}></i></span>
                    </div>
                    {/* error message text */}
                    {errors.password && (
                        <p className="error-msg">
                            {errors.password?.message}
                        </p>
                    )}
                </div>
                {/* Forget password */}
                <div className={`flex justify-end items-center mb-4`}>
                    <p className="fs-14">
                        <button type="button" className='text-primaryColor' onClick={() => { dispatch(commonActions.setLRFFlow('forgot-password')); }}>{CreateProfileContent.LOGIN.FORGOT_PASSWORD}</button>
                    </p>
                </div>
                {/* Forget password end */}
                <button className={`w-full SecondaryBtn`} name='login' type='submit'>{CreateProfileContent?.FORM?.LOGIN}</button>
            </form>
        </>
    )
}

export default LoginForm