import React from 'react';
import { Button, FormItem, FormContainer } from '@/components/ui';
import { Field, Form, Formik } from 'formik';
import * as Yup from 'yup';
import { useTranslation } from 'react-i18next';
import { PasswordInput } from '@/components/shared';
import PasswordStrengthBar from 'react-password-strength-bar'; // Import the PasswordStrengthBar component
import { useSelector } from 'react-redux';
import useTimeOutMessage from '@/utils/hooks/useTimeOutMessage';
import { apiNewPassword } from '@/services/AuthService';
import NalertToast from '@/nafith/alertToast';
import { useNavigate } from 'react-router-dom';
import { clearData } from '../store/dataSlice';
import { clearCurrentStep } from '../store/stateSlice';

const NewPassword = ({
  data = {
    newPassword: '',
    confirmPassword: '',
  },
  onNextChange,
  currentStepStatus,
}) => {
  const { t } = useTranslation();
  const navigate = useNavigate();

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

  const formData = useSelector((state) => state.accountDetailForm.data.formData);
  const [message, setMessage] = useTimeOutMessage();
  const onCreatePassword = async (values, setSubmitting) => {
    const phoneNumber = formData?.UserInformation?.dialCode + formData?.UserInformation?.authorizedManagerMobileNo;
    try {
      const resp = await apiNewPassword(values, phoneNumber);
      if (resp.data) {
        //onNext(values, setSubmitting);
        NalertToast(t('THR_OPERATION_ACCOMPLISHED_SUCCESSFULLY'), 'success');
        clearData();
        clearCurrentStep();
        navigate('/ewaybill/sign-in');
        setSubmitting(false);
      }
    } catch (errors) {
      setMessage(t(errors?.response?.data?.errorCodes[0].errorMessages) || errors.toString());
      setSubmitting(false);
    }
  };

  const validationSchema = Yup.object().shape({
    newPassword: Yup.string()
      .min(8, t('PASSWORD_MUST_BE_AT_LEAST_8_CHARACTERS'))
      .max(25, t('PASSWORD_MUST_BE_AT_MOST_15_CHARACTERS'))
      .matches(
        // eslint-disable-next-line no-useless-escape
        /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*()_\-+=\[\]{}|;:,.<>?])[A-Za-z\d!@#$%^&*()_\-+=\[\]{}|;:,.<>?]+$/,
        t(
          'PASSWORD_MUST_CONTAIN_AT_LEAST_ONE_LOWERCASE_LETTER_ONE_UPPERCASE_LETTER_ONE_DIGIT_AND_ONE_SPECIAL_SYMBOL_IN_THE_LIST',
        ) + ' (!@#$%^&*()_-+=[]{}|;:,.<>?)',
      )
      .required(t('THIS_FIELD_IS_REQUIRED')),
    confirmPassword: Yup.string()
      .oneOf([Yup.ref('newPassword'), null], t('PASSWORD_MUST_MATCH'))
      .required(t('PLEASE_CONFIRM_YOUR_PASSWORD')),
  });

  return (
    <>
      <div className="mb-8">
        {message && <div className="text-red-500 text-sm mb-2">{message}</div>}
        <h3 className="mb-2">{t('CREATE_PASSWORD')}</h3>
        <p className="text-sm text-gray-500">
          {t(
            'PASSWORD_MUST_CONTAIN_AT_LEAST_ONE_LOWERCASE_LETTER_ONE_UPPERCASE_LETTER_ONE_DIGIT_AND_ONE_SPECIAL_SYMBOL_IN_THE_LIST',
          ) + ' (!@#$%^&*()_-+=[]{}|;:,.<>?)'}
        </p>
      </div>
      <Formik
        initialValues={data}
        enableReinitialize={true}
        validationSchema={validationSchema}
        onSubmit={(values, { setSubmitting }) => {
          setSubmitting(true);
          onCreatePassword(values, setSubmitting);
        }}
      >
        {({ values, touched, errors, isSubmitting }) => {
          return (
            <Form>
              <FormContainer>
                <div className="md:grid grid-cols-2 gap-4">
                  <div className="col-span-1">
                    <FormItem
                      label={t('NEW_PASSWORD')}
                      invalid={errors.newPassword && touched.newPassword}
                      errorMessage={errors.newPassword}
                    >
                      <Field
                        name="newPassword"
                        placeholder={t('PASSWORD')}
                        component={PasswordInput}
                        autoComplete="off"
                      />
                    </FormItem>
                    {/* Add the PasswordStrengthBar component to show password strength */}
                    <PasswordStrengthBar
                      password={values.newPassword}
                      // scoreWords={['WEAK', 'WEAK', 'FAIR', 'STRONG', 'VERY_STRONG']}
                      scoreWords={[t('WEAK'), t('FAIR'), t('GOOD'), t('STRONG'), t('STRONGER')]}
                      shortScoreWord={false}
                    />
                  </div>
                </div>
                <div className="md:grid grid-cols-2 gap-4">
                  <FormItem
                    label={t('CONFIRM_PASSWORD')}
                    invalid={touched.confirmPassword && errors.confirmPassword}
                    errorMessage={errors.confirmPassword}
                  >
                    <Field
                      name="confirmPassword"
                      placeholder={t('CONFIRM_PASSWORD')}
                      component={PasswordInput}
                      autoComplete="off"
                    />
                  </FormItem>
                </div>
                <div className="flex justify-end gap-2">
                  {/* <Button type="button" onClick={onBack}>
                    {t('BACK')}
                  </Button> */}
                  <Button
                    loading={isSubmitting}
                    variant="solid"
                    type="submit"
                    color="success"
                    disabled={!values.newPassword || errors.newPassword || errors.confirmPassword}
                    className={
                      values.newPassword && !errors.newPassword && !errors.confirmPassword
                        ? 'bg-green-500 hover:bg-green-600'
                        : 'bg-gray-300 cursor-not-allowed'
                    }
                  >
                    {t('SUBMIT')}
                  </Button>
                </div>
              </FormContainer>
            </Form>
          );
        }}
      </Formik>
    </>
  );
};

export default NewPassword;
