'use client'
/* 
  This is the verification code component.
  It contains the following components:
  - VerificationCode
*/
import { RootState } from '@/redux/slices';
import { commonActions } from '@/redux/slices/Common/commonSlice';
import { AppDispatch } from '@/redux/store';
import { resendOTP, verifyOTP } from '@/redux/thunks/Auth/authentication.thunk';
import { ResendOTPPayload, VerifyOTPPayload } from '@/redux/types/authenticationTypes';
import OtpInputControl from "@/src/components/page/Auth/OtpInputControl";
import { Toast } from '@/src/components/Toast';
import { LRFFlowContent } from '@/src/types/StaticContent/lrfflow.content.type';
import { FormatTime } from '@/src/utils/commonFunctions';
import { COMMON_VARS } from '@/src/utils/commonVariables';
import { useDebounce } from '@/src/utils/customHooks/useDebounce';
import { zodResolver } from "@hookform/resolvers/zod";
import React, { useEffect, useState } from 'react';
import { Controller, useForm } from "react-hook-form";
import { useDispatch, useSelector } from 'react-redux';
import { z } from "zod";
import { VerificationFormData } from '../../../Form/AuthTypes/AuthTypes';
import styles from './VerificationCode.module.scss';

// Define the props type for the VerificationCode componen

const VerificationCode: React.FC<{ CreateProfileContent: LRFFlowContent }> = ({ CreateProfileContent }) => {

  const dispatch = useDispatch<AppDispatch>();
  const [otp, setOtp] = useState("");
  const [count, setCount] = useState(0);
  const [resendOTPCounter, setResendOTPCounter] = useState(COMMON_VARS.RESEND_OTP_TIME);
  // Get the current LRFFlow state
  const { LRFFlow } = useSelector((state: RootState) => state?.common)
  const { emailLRFData } = useSelector((state: RootState) => state?.authentication)

  /**
  * Schema for validating user verification form data using Zod.
  * This schema ensures all required fields are filled with valid data
  * and enforces specific validation rules for each input.
  */
  const VerificationSchema = z.object({
    otp: z
      .string()
      .min(1, { message: CreateProfileContent.FORM.OTP_REQUIRED }) // Required field
      .min(COMMON_VARS.OTP_LENGTH, {
        message: CreateProfileContent.FORM.OTP_MIN_LENGTH,
      }),
  });

  /**
   * Initializes the useForm hook for managing form state and validation.
   *
   * @typedef {VerificationFormData} - The expected data structure for the verify otp form.
   */
  const {
    handleSubmit,
    formState: { errors },
    control,
    setValue
  } = useForm<VerificationFormData>({
    /**
     * Resolver integrates Zod schema validation into React Hook Form.
     * Ensures validation logic defined in `VerificationSchema` is applied.
     */
    //@ts-ignore
    resolver: zodResolver(VerificationSchema),
    /**
     * Mode configuration for when validation should occur.
     * - `"onChange"`: Validates fields on every change.
     * - Ensures instant feedback for better UX.
     */
    mode: "onChange",
    delayError: 1000,
  });


  /**
   * Handles the verify otp process by preparing the payload and dispatching the verify otp action.
   * Dispatches verification action and handles navigation based on response
  */
  const handleOTPVerification = () => {
    /* Construct the payload for the verify otp API request */
    const payload: VerifyOTPPayload = {
      otp: Number(otp),
      email: emailLRFData,
      isForgotPassword: LRFFlow === 'forgot-password-otp-verification' ? true : false,
    };

    dispatch(
      verifyOTP(payload, (data) => {
        /* Show success/error message */
        if (data?.meta?.status) {
          Toast("success", data?.meta?.message)
          if (LRFFlow === 'forgot-password-otp-verification') {
            // Push the user to the set new password page
            dispatch(commonActions.setLRFFlow('set-new-password'))
          } else {
            // Push the user to the profile created page
            dispatch(commonActions.setLRFFlow('profile-created'))
          }
        } else {
          Toast("error", data?.meta?.message)
        }
      })
    );

  };

  /* Resend OTP automatically after 60 seconds */
  useEffect(() => {
    if (resendOTPCounter == 0 && count < 2) {
      handleResendOTP()
      setResendOTPCounter(COMMON_VARS.RESEND_OTP_TIME)
      setCount(count + 1)
    }
  }, [resendOTPCounter]);

  /* Debounced handle OTP verification */
  const debouncedHandleOTPVerification = useDebounce(() => {
    handleOTPVerification()
  }, COMMON_VARS.DELAY_DEBOUNCE)

  /* Handle OTP verification on input change */
  useEffect(() => {
    if (otp.length === COMMON_VARS.OTP_LENGTH) {
      debouncedHandleOTPVerification()
    }
  }, [otp])

  /* Resend OTP counter */
  useEffect(() => {
    const time = setInterval(() => {
      setResendOTPCounter((prev) => prev - 1);
    }, 1000)
    return () => {
      clearInterval(time)
    }
  }, [])

  /**
   * Handles OTP resend request
   * Dispatches resend action and shows status message
   */
  const handleResendOTP = () => {
    /* Construct the payload for the verify otp API request */
    const payload: ResendOTPPayload = {
      email: emailLRFData,
      isProfile: false,
      isForgotPassword: false,
    };

    dispatch(
      resendOTP(payload, (data) => {
        /* Show success/error message */
        if (data?.meta?.status) {
          Toast("success", data?.meta?.message)
        } else {
          Toast("error", data?.meta?.message)
        }
      })
    );
  };

  return (
    <>
      <form
        onSubmit={handleSubmit(handleOTPVerification)}
        className={`${styles.PassResetForm}`}
      >
        {/* Password reset OTP input wrapper */}
        <div className={`${styles.PassresetWrapper} flex gap-2.5`}>
          <div className="InputWrapper w-full">
            <Controller
              name="otp"
              control={control}
              render={({ field: { onChange } }) => (
                <>
                  <OtpInputControl
                    autoFocus
                    isNumberInput
                    length={COMMON_VARS.OTP_LENGTH}
                    onChangeOTP={(otp: string) => {
                      onChange(otp);
                      setOtp(otp);
                    }}
                  />
                </>
              )}
            />
          </div>
          {/* error message text */}
          {/* {errors.otp && <p className="error-msg">{errors.otp?.message}</p>} */}
        </div>
        {/* Password reset OTP input wrapper end*/}

        <button className="SecondaryBtn max-w-[300px] w-full mx-auto mt-[20px] md:mt-[25px] xl:mt-[30px]" type="submit" >
          {CreateProfileContent.FORM.CONTINUE}
        </button>
      </form>

      {/* Recent OTP Section */}
      {/* <div className={`AuthAlreadyBox`}>
        <p className="fs-16">
          {`Didn't receive the email?`}{' '}
          <button className={false ? 'pointer-events-none text-primaryColor' : 'text-primaryColor'} onClick={(e) => {
            e.preventDefault()
          }}>{'Click here'}</button>
        </p>
      </div> */}
      <div className={`AuthAlreadyBox`}>
        <div className="!text-center fs-14">
          {resendOTPCounter > 0 && count < 3 ? (
            <>
              {CreateProfileContent.FORM.DIDNT_RECEIVE_THE_CODE}
            </>
          ) : (
            <>
              <p className='!text-center'>{CreateProfileContent.FORM.DIDNT_RECEIVE_THE_CODE_VIA_EMAIL}</p>
              <div className='flex items-center justify-center gap-1'>
                <button type='button' className={(resendOTPCounter > 0 && count < 3) ? 'pointer-events-none text-primaryColor' : 'text-primaryColor'} onClick={(e) => {
                  e.preventDefault()
                  handleResendOTP()
                  setCount(2)
                  setResendOTPCounter(COMMON_VARS.RESEND_OTP_TIME)
                }}>{CreateProfileContent.FORM.RESEND}</button>
                <p> or </p>
                <button type='button' className={(resendOTPCounter > 0 && count < 3) ? 'pointer-events-none text-primaryColor' : 'text-primaryColor'} onClick={(e) => {
                  e.preventDefault()
                  dispatch(commonActions.setLRFFlow('forgot-password'))
                }}>{CreateProfileContent.FORM.CHANGE_EMAIL}</button>
              </div>
            </>
          )}
        </div>
        <p className="!text-center fs-14">
          {resendOTPCounter > 0 && count < 3 ? (
            <>
              {CreateProfileContent.FORM.WE_WILL_SEND_NEW_CODE} {' '}
              <span className='text-primaryColor inline-block min-w-[47px]'>{FormatTime(resendOTPCounter)}</span> {' '}
              {CreateProfileContent.FORM.MINUTES}
            </>
          ) : null}
        </p>
      </div>
      {/* Recent OTP Section end */}
    </>
  )
}

export default VerificationCode