import { useFormContext } from 'react-hook-form';

import { IconCheck, IconPointFilled } from '@material-hu/icons/tabler';
import Stack from '@material-hu/mui/Stack';
import { useTheme } from '@material-hu/mui/styles';
import Typography from '@material-hu/mui/Typography';

import HuFormInputPassword from '@material-hu/components/design-system/Inputs/Password/form';

import useRules from 'src/hooks/useRules';
import { PasswordType } from 'src/types/instance';
import { useLokaliseTranslation } from 'src/utils/i18n';
import {
  getRulesOfStrongPassword,
  checkPasswordType,
  getCorrectColorTextStrongPassword,
} from 'src/utils/validation';

const defaultPasswordType = { validateMinLength: true };

type HuFormStrongPasswordProps = {
  passwordType: PasswordType | null;
};

const HuFormStrongPassword = (props: HuFormStrongPasswordProps) => {
  const { passwordType } = props;
  const finalPasswordType = passwordType || defaultPasswordType;

  const { t } = useLokaliseTranslation('authentication');
  const theme = useTheme();

  const {
    trigger,
    formState: { isSubmitting, touchedFields, dirtyFields },
    setValue,
    watch,
  } = useFormContext();

  const password = watch('passwordInput');

  const passwordRules = useRules({
    requiredWithMessage: true,
    ...getRulesOfStrongPassword(finalPasswordType),
  });

  const repeatPasswordRules = useRules({
    requiredWithMessage: true,
    equal: { value: password, message: t('REPEAT_PASSWORD_ERROR') },
  });

  const validation = checkPasswordType(finalPasswordType, t, password);

  return (
    <>
      <Stack sx={{ width: '100%' }}>
        <HuFormInputPassword
          name="passwordInput"
          rules={passwordRules}
          customOnChange={async value => {
            // esto resuelve el siguiente error: https://github.com/react-hook-form/react-hook-form/issues/227#issuecomment-952158935
            await setValue('passwordInput', value, {
              shouldDirty: true,
              shouldTouch: true,
            });
            trigger('passwordInput');
            if (touchedFields.repeatPasswordInput) {
              trigger('repeatPasswordInput');
            }
          }}
          inputProps={{
            id: 'passwordInput',
            label: t('UPDATE.CREATE_PASSWORD'),
            disabled: isSubmitting,
          }}
        />
      </Stack>
      <Stack sx={{ width: '100%' }}>
        <HuFormInputPassword
          name="repeatPasswordInput"
          customOnChange={async value => {
            await setValue('repeatPasswordInput', value, {
              shouldDirty: true,
              shouldTouch: true,
            });
            trigger('repeatPasswordInput');
          }}
          rules={repeatPasswordRules}
          inputProps={{
            id: 'repeatPasswordInput',
            label: t('UPDATE.REPEAT_PASSWORD'),
            disabled: isSubmitting,
          }}
        />
        {validation.map(elem => {
          const color = getCorrectColorTextStrongPassword(
            dirtyFields.passwordInput,
            elem.isValid,
            theme,
          );
          return (
            <Stack
              key={elem.text}
              sx={{
                flexDirection: 'row',
                my: 1,
                gap: 0.5,
                width: '100%',
                alignItems: 'center',
              }}
            >
              {elem.isValid && (
                <IconCheck
                  size={16}
                  color={color}
                />
              )}
              {!elem.isValid && (
                <IconPointFilled
                  size={16}
                  color={color}
                />
              )}
              <Typography
                variant="globalS"
                sx={{ color }}
              >
                {elem.text}
              </Typography>
            </Stack>
          );
        })}
      </Stack>
    </>
  );
};

export default HuFormStrongPassword;
