'use client'
/*
  This component is for the forgot password.
  It includes a form with an email input and a continue button.
  It also includes a button to go back to the create profile page.
*/
import { commonActions } from '@/redux/slices/Common/commonSlice';
import { AppDispatch } from '@/redux/store';
import { forgotPassword } from '@/redux/thunks/Auth/authentication.thunk';
import { Toast } from '@/src/components/Toast';
import { LRFFlowContent } from '@/src/types/StaticContent/lrfflow.content.type';
import { REGEX } from '@/src/utils/commonVariables';
import { zodResolver } from '@hookform/resolvers/zod';
import { useForm } from 'react-hook-form';
import { useDispatch } from 'react-redux';
import { z } from 'zod';

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

    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 ForgotPasswordSchema = z.object({
        /**
         * Email - Required and must match the defined email pattern.
         */
        email: z
            .string()
            .min(1, { message: CreateProfileContent.FORM.EMAIL_REQUIRED }) // Required field
            .regex(REGEX.EMAIL, { message: CreateProfileContent.FORM.EMAIL_INVALID }), // Must follow email pattern
    });

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

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

        const payload = {
            email: formValues.email
        }

        /* Dispatch the login action with the payload and a callback function */
        dispatch(
            forgotPassword(payload, (data) => {
                /* Display success/error message upon api success/failure */
                if (data?.meta?.status) {
                    Toast("success", data?.meta?.message)
                    dispatch(commonActions.setLRFFlow('forgot-password-otp-verification'))
                } else {
                    Toast("error", data?.meta?.message)
                }
            })
        );
    };

    return (
        <>
            <form onSubmit={handleSubmit(handleForgotPassword)}>
                <div className="InputWrapper">
                    <label htmlFor="email">{'Email'}</label>
                    <input
                        className={`!bg-bgColor !fs-16`}
                        type="email"
                        id="email"
                        placeholder={CreateProfileContent.FORM.ENTER_EMAIL}
                        {...register('email')}
                    />
                    {/* error message text */}
                    {errors.email && (
                        <p className="error-msg">
                            {errors.email?.message as string}
                        </p>
                    )}
                </div>
                <button className={`w-full SecondaryBtn`} name='login' type='submit' >{CreateProfileContent.FORM.CONTINUE}</button>
            </form>
        </>
    )
}

export default ForgotPassword