'use client'
import { RootState } from '@/redux/slices';
import { commonActions } from '@/redux/slices/Common/commonSlice';
import { AppDispatch } from '@/redux/store';
import { resetPassword } from '@/redux/thunks/Auth/authentication.thunk';
import { ResetPasswordPayload } from '@/redux/types/authenticationTypes';
import PasswordValidations from '@/src/components/Form/PasswordValidations/PasswordValidations';
import { Toast } from '@/src/components/Toast';
import { LRFFlowContent } from '@/src/types/StaticContent/lrfflow.content.type';
import { COMMON_VARS, REGEX, STRENGTH_LEVELS } from '@/src/utils/commonVariables';
import { getPasswordStrength } from '@/src/utils/passwordValidation';
import { zodResolver } from "@hookform/resolvers/zod";
import { useRouter } from 'next/navigation';
import { useEffect, useState } from 'react';
import { useForm } from "react-hook-form";
import { useDispatch, useSelector } from 'react-redux';
import { z } from "zod";
import styles from './CreateProfile.module.scss';

const SetNewPassword = ({ SetNewPasswordContent }: { SetNewPasswordContent: LRFFlowContent['SET_NEW_PASSWORD'] }) => {

    const router = useRouter();
    const dispatch = useDispatch<AppDispatch>();
    const [showPassword, setShowPassword] = useState(false);
    const [showRePassword, setShowRePassword] = useState(false);
    const { emailLRFData } = useSelector((state: RootState) => state?.authentication)

    /**
     * Schema for validating user set new password form data using Zod.
     * This schema ensures all required fields are filled with valid data
     * and enforces specific validation rules for each input.
     */
    const SetNewPasswordSchema = z.object({
        /**
         * Password - Required, must have a minimum of 8 characters.
         */
        password: z
            .string()
            .min(1, { message: SetNewPasswordContent.FORM.PASSWORD_REQUIRED }) // Required field
            .min(COMMON_VARS.MIN_PASSOWRD_LENGTH, { message: SetNewPasswordContent.FORM.PASSWORD_MIN_LENGTH }) // Minimum 8 characters
            .regex(REGEX.PASSWORD, { message: SetNewPasswordContent.FORM.PASSWORD_INVALID }) // Must follow password pattern
            .trim(), // Removes leading/trailing spaces

        /**
         * Confirm Password - Required and must match the `password` field.
         */
        confirmPassword: z
            .string()
            .min(1, { message: SetNewPasswordContent.FORM.CONFIRM_PASSWORD_REQUIRED }) // Required field
            .trim() // Removes leading/trailing spaces
    })
        .refine((data) => data.password === data.confirmPassword, {
            path: ["confirmPassword"],
            message: SetNewPasswordContent.FORM.PASSWORD_NOT_MATCHED,
        });
    /**
     * Initializes the useForm hook for managing form state and validation.
     *
     * @typedef {any} - The expected data structure for the form.
     */
    const {
        handleSubmit,
        formState: { errors },
        register,
        watch,
        trigger
    } = useForm<any>({
        /**
         * Resolver integrates Zod schema validation into React Hook Form.
         * Ensures validation logic defined in `SignUpSchema` is applied.
         */
        // @ts-ignore
        resolver: zodResolver(SetNewPasswordSchema),
        /**
         * Mode configuration for when validation should occur.
         * - `"onChange"`: Validates fields on every change.
         * - Ensures instant feedback for better UX.
         */
        mode: "onChange",
    });

    /* Manually re-validates confirmPassword when password changes */
    useEffect(() => {
        const subscription = watch((_, { name }) => {
            if (name === "password" && watch("confirmPassword")) {
                trigger("confirmPassword");
            }
        });

        return () => subscription.unsubscribe();
    }, [watch, trigger]);

    let passwordStrength = getPasswordStrength(watch("password"));
    const activeCount = Math.max(0, Math.min(3, passwordStrength));
    const strengthClass = STRENGTH_LEVELS[activeCount - 1]?.className || "weak";

    //handle reset password
    const handleResetPassword = (formValues: any) => {

        const payload: ResetPasswordPayload = {
            email: emailLRFData,
            password: formValues.password,
            confirmPassword: formValues.confirmPassword,
        };
        /* Dispatch the reset action with the payload and a callback function */
        dispatch(
            resetPassword(payload, (data) => {
                /* Display success/error message upon api success/failure */
                if (data?.meta?.status) {
                    dispatch(commonActions.setLRFFlow('forgot-password-success'))
                } else {
                    Toast("error", data?.meta?.message)
                }
            })
        );
    }

    //handle continue navigation
    const handleContinueNavigation = () => {
        dispatch(commonActions.setLRFFlow('login'))
    }

    return (
        <>
            <form onSubmit={handleSubmit(handleResetPassword)}>
                {/* Password wrapper */}
                <div className="InputWrapper">
                    <label htmlFor="password">{SetNewPasswordContent.FORM.PASSWORD}</label>
                    <div className='relative'>
                        <input
                            type={showPassword ? 'text' : 'password'}
                            id="password"
                            value={watch("password") ?? ""}
                            className={`!bg-bgColor !fs-16 !pr-10`}
                            placeholder={SetNewPasswordContent.FORM.ENTER_PASSWORD}
                            {...register("password", {
                                onChange: (e) =>
                                    getPasswordStrength(e.target.value),
                            })}
                        />
                        <span onClick={() => setShowPassword(prev => !prev)} className={`absolute top-1/2 -translate-y-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 ${passwordStrength > 0 ? '!bottom-[22px]' : ''}`}>{errors.password?.message as string}</p>
                    )}
                    {/* Password strength */}
                    {passwordStrength > 0 && <PasswordValidations styles={styles} activeCount={activeCount} strengthClass={strengthClass} />}
                    {/* Password strength end */}
                </div>
                {/* Password wrapper end */}
                {/* Confirm password wrapper */}
                <div className="InputWrapper">
                    <label htmlFor="confirmpassword">{SetNewPasswordContent.FORM.CONFIRM_PASSWORD}</label>
                    <div className='relative'>
                        <input
                            type={showRePassword ? 'text' : 'password'}
                            id="confirmpassword"
                            className={`!bg-bgColor !fs-16 !pr-10`}
                            value={watch("confirmPassword") ?? ""}
                            placeholder={SetNewPasswordContent.FORM.RE_ENTER_PASSWORD}
                            {...register("confirmPassword")}
                        />
                        <span onClick={() => setShowRePassword(prev => !prev)} className={`absolute top-1/2 -translate-y-1/2 right-3 cursor-pointer`}><i className={`!bg-grey85 !w-[18px] !h-[18px] Icon ${showRePassword ? 'IconEyeClose' : 'IconEyeOpenPassword'}`}></i></span>
                    </div>
                    {/* error message text */}
                    {errors.confirmPassword && (
                        <p className="error-msg">{errors.confirmPassword?.message as string}</p>
                    )}
                </div>
                {/* Confirm password wrapper end */}

                <button className={`w-full SecondaryBtn mt-2`} name='Continue' type='submit'>{SetNewPasswordContent.FORM.CONTINUE}</button>
            </form>
        </>
    )
}

export default SetNewPassword