import React, { useState } from 'react';

import { Button, FormContainer } from '@/components/ui';
import FormDesription from './FormDesription';
import FormRow from './FormRow';
import { Field, Form, Formik } from 'formik';
/*
import { HiOutlineDesktopComputer, HiOutlineDeviceMobile, HiOutlineDeviceTablet } from 'react-icons/hi';
*/
import * as Yup from 'yup';
import { apiChangePassword } from '@/services/AccountServices';
import NalertToast from '@/nafith/alertToast';
import { t } from 'i18next';
import { PasswordInput } from '@/components/shared';
import PasswordStrengthBar from 'react-password-strength-bar';
/*
const LoginHistoryIcon = ({ type }) => {
  switch (type) {
    case 'Desktop':
      return <HiOutlineDesktopComputer />;
    case 'Mobile':
      return <HiOutlineDeviceMobile />;
    case 'Tablet':
      return <HiOutlineDeviceTablet />;
    default:
      return <HiOutlineDesktopComputer />;
  }
};*/

const Password = ({ data }) => {
  const [disabledButton, setDisabledButton] = useState(false);

  const validationSchema = Yup.object().shape({
    OldPassword: Yup.string().required(t('THIS_FIELD_IS_REQUIRED')),
    NewPassword: Yup.string()
      .min(8, t('PASSWORD_MUST_BE_AT_LEAST_8_CHARACTERS'))
      .max(25, t('PASSWORD_MUST_BE_LESS_THAN_25_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'))
      .test('not-same', t('NEW_PASSWORD_MUST_BE_DIFFERENT_FROM_OLD_PASSWORD'), function (value) {
        return value !== this.parent.OldPassword;
      }),
    ConfirmPassword: Yup.string()
      .oneOf([Yup.ref('NewPassword'), null], t('PASSWORDS_MUST_MATCH'))
      .required(t('THIS_FIELD_IS_REQUIRED')),
  });

  const onFormSubmit = async (values, setSubmitting) => {
    // setSubmitting(true);
    try {
      const resp = await apiChangePassword(values);
      if (resp.data) {
        setSubmitting(false);
        values.OldPassword = '';
        values.NewPassword = '';
        values.ConfirmPassword = '';
        NalertToast(resp?.data?.errorCodes[0]?.errorMessages, 'success');
      }
    } catch (errors) {
      NalertToast(errors?.response?.data?.errorCodes || errors.toString(), 'danger');
      setSubmitting(false);
      setDisabledButton(true);
      setTimeout(() => {
        setDisabledButton(false);
      }, 3000);
    }
    setSubmitting(false);
  };

  return (
    <>
      <Formik
        initialValues={{
          OldPassword: '',
          NewPassword: '',
          ConfirmPassword: '',
          Email: data?.email || '',
          PhoneNumber: data?.mobileNo || '',
        }}
        validationSchema={validationSchema}
        onSubmit={(values, { setSubmitting }) => {
          setSubmitting(true);
          setTimeout(() => {
            onFormSubmit(values, setSubmitting);
          }, 1000);
        }}
      >
        {({ values, touched, errors, isSubmitting, resetForm }) => {
          const validatorProps = { touched, errors };
          return (
            <Form>
              <FormContainer>
                <FormDesription
                  title={t('Update Password')}
                  desc={t('Enter your current & new password to reset your password')}
                />

                <FormRow name="OldPassword" label={t('Current Password')} {...validatorProps}>
                  <Field
                    type="password"
                    autoComplete="off"
                    name="OldPassword"
                    placeholder={t('Current Password')}
                    component={PasswordInput}
                  />
                </FormRow>
                <FormRow name="NewPassword" label={t('New Password')} {...validatorProps}>
                  <Field
                    type="password"
                    autoComplete="off"
                    name="NewPassword"
                    placeholder={t('New Password')}
                    component={PasswordInput}
                  />
                  {/* Add the PasswordStrengthBar component to show password strength */}
                  <PasswordStrengthBar
                    className="mt-3"
                    password={values.NewPassword}
                    scoreWords={[t('WEAK'), t('FAIR'), t('GOOD'), t('STRONG'), t('STRONGER')]}
                    shortScoreWord={false}
                  />
                </FormRow>
                <FormRow name="ConfirmPassword" label={t('Confirm Password')} {...validatorProps}>
                  <Field
                    type="password"
                    autoComplete="off"
                    name="ConfirmPassword"
                    placeholder={t('Confirm Password')}
                    component={PasswordInput}
                  />
                </FormRow>
                <div className="mt-4 ltr:text-right rtl:text-left">
                  {/* <Button className="ltr:mr-2 rtl:ml-2" type="button" onClick={resetForm}>
                    {t('Reset')}
                  </Button> */}
                  <Button variant="solid" loading={isSubmitting} type="submit" disabled={disabledButton}>
                    {isSubmitting ? t('Updating') + '...' : t('Update Password')}
                  </Button>
                </div>
              </FormContainer>
            </Form>
          );
        }}
      </Formik>
    </>
  );
};

export default Password;
