import { Input, Button, FormItem, FormContainer } from '@/components/ui';
import { Field, Form, Formik } from 'formik';
import NumberFormat from 'react-number-format';
import * as Yup from 'yup';
import { useTranslation } from 'react-i18next';
import { useSelector } from 'react-redux';
import { apiSendOTP, apiVerifyOTP } from '@/services/AuthService';
import useTimeOutMessage from '@/utils/hooks/useTimeOutMessage';
import { useState } from 'react';
import { ResendOtpButton } from '@/nafith/shared';

const NumberFormatInput = ({ onValueChange, ...rest }) => {
  return (
    <NumberFormat
      customInput={Input}
      type="text"
      onValueChange={onValueChange}
      autoComplete="off"
      {...rest}
      allowNegative={false}
      decimalScale={0}
    />
  );
};

const VerificationOTP = ({
  data = {
    verificationCode: '',
  },
  onNextChange,
}) => {
  const { t } = useTranslation();
  const formData = useSelector((state) => state.accountDetailForm.data.formData);
  const [message, setMessage] = useTimeOutMessage();
  const [resendOTP, setResendOTP] = useState(false);
  const [blockedResendOTP, setBlockedResendOTP] = useState(false);

  const onVerifyOTP = async (values, setSubmitting) => {
    setSubmitting(true);
    const phoneNumber = formData?.UserInformation?.dialCode + formData?.UserInformation?.authorizedManagerMobileNo;
    try {
      const resp = await apiVerifyOTP(values, phoneNumber);
      if (resp.data) {
        setSubmitting(false);
        onNext(values, setSubmitting);
      }
    } catch (errors) {
      setMessage(t(errors?.response?.data?.errorCodes[0].errorMessages) || errors.toString());
      setSubmitting(false);
    }
  };
  const onResendOTP = async (values, setSubmitting) => {
    setSubmitting(true);
    setResendOTP(true);
    const phoneNumber = formData?.UserInformation?.dialCode + formData?.UserInformation?.authorizedManagerMobileNo;
    try {
      const resp = await apiSendOTP(values, phoneNumber);
      if (resp.data) {
        setSubmitting(false);
        setResendOTP(false);
      }
    } catch (errors) {
      setSubmitting(false);
      setResendOTP(false);
      if (errors?.response?.data?.responseCode === '429') {
        setBlockedResendOTP(true);
      }
      setMessage(t(errors?.response?.data?.errorCodes[0].errorMessages) || errors.toString());
    }
  };

  const onNext = (values, setSubmitting) => {
    onNextChange?.(values, 'VerificationOTP', setSubmitting);
  };

  const validationSchema = Yup.object().shape({
    verificationCode: Yup.string()
      .matches(/^[0-9]{6}$/, t('PLEASE_ENTER_VALID_OTP'))
      .required(t('THIS_FIELD_IS_REQUIRED')),
  });
  return (
    <>
      <div className="mb-8">
        <h3 className="mb-2">{t('VERIFICATION_OTP')}</h3>
        <p>
          {t('A_OTP_One_Time_Password_HAS_BEEN_SENT_TO_YOUR_REGISTERED_MOBILE_NUMBER') + ' '}
          <span className="font-bold ltr-direction">
            ({formData?.UserInformation?.dialCode?.replace('+', '00')}
            {formData?.UserInformation?.authorizedManagerMobileNo})
          </span>
        </p>
        <p>{t('PLEASE_ENTER_THE_OTP_BELOW_TO_VERIFY_YOUR_MOBILE_NUMBER')}</p>
      </div>
      <Formik
        initialValues={data}
        enableReinitialize={true}
        validationSchema={validationSchema}
        onSubmit={(values, { setSubmitting }) => {
          setSubmitting(true);
          setTimeout(() => {
            onVerifyOTP(values, setSubmitting);
          }, 10);
        }}
      >
        {({ values, touched, errors, isSubmitting, setSubmitting }) => {
          return (
            <Form>
              <FormContainer>
                <div className="mb-4">
                  <p className="text-red-500">{message}</p>
                </div>

                <div className="md:grid grid-cols-2 gap-4">
                  <FormItem
                    label={t('VERIFICATION_CODE')}
                    invalid={errors.verificationCode && touched.verificationCode}
                    errorMessage={errors.verificationCode}
                  >
                    <Field name="verificationCode">
                      {({ field, form }) => {
                        return (
                          <NumberFormatInput
                            form={form}
                            maxLength={12}
                            field={field}
                            customInput={Input}
                            format="######"
                            placeholder={t('VERIFICATION_CODE')}
                            onValueChange={(e) => {
                              form.setFieldValue(field.name, e.value);
                            }}
                          />
                        );
                      }}
                    </Field>
                    {/* resend otp */}
                    <ResendOtpButton
                      onResendClick={() => {
                        onResendOTP(values, setSubmitting);
                      }}
                      resendOTP={resendOTP} // Pass the resendOTP status here
                      blockedResendOTP={blockedResendOTP}
                      // disableSubmit={disableSubmit}
                    />
                  </FormItem>
                </div>

                <div className="flex justify-end gap-2">
                  {/* <Link to="/sign-in">
                    <Button type="button">{t('BACK')}</Button>
                  </Link> */}
                  <Button loading={isSubmitting} variant="solid" type="submit">
                    {t('NEXT')}
                  </Button>
                </div>
              </FormContainer>
            </Form>
          );
        }}
      </Formik>
    </>
  );
};

export default VerificationOTP;
