import React, {useEffect} from 'react';
import {Check, COLOR, SIZE} from '@propellerads/icon';

import {DefaultRulesParams, PasswordValidatorProps} from './types';

import {StyledPasswordValidator, PasswordRule, PasswordIcon} from './style';

export const getDefaultRules = ({
  passwordChangeRuleLengthText,
  passwordChangeRuleLatinLowercaseText,
  passwordChangeRuleLatinUppercaseText,
  passwordChangeRuleDigitsText,
  passwordChangeRuleIsEqualText,
}: DefaultRulesParams) => [
  {
    test: (value: string) => value.length >= 8,
    label: passwordChangeRuleLengthText,
    key: 'passwordChangeRuleLengthText',
  },
  {
    test: (value: string) => /[a-z]/.test(value),
    label: passwordChangeRuleLatinLowercaseText,
    key: 'passwordChangeRuleLatinLowercaseText',
  },
  {
    test: (value: string) => /[A-Z]/.test(value),
    label: passwordChangeRuleLatinUppercaseText,
    key: 'passwordChangeRuleLatinUppercaseText',
  },
  {
    test: (value: string) => /\d/.test(value),
    label: passwordChangeRuleDigitsText,
    key: 'passwordChangeRuleDigitsText',
  },
  {
    test: (oneValue: string, twoValue: string) => (oneValue && twoValue) && oneValue === twoValue,
    label: passwordChangeRuleIsEqualText,
    key: 'passwordChangeRuleIsEqualText',
  },
];

const PasswordValidator = ({
  rules,
  password = '',
  confirmPassword = '',
  onTestsPassed,
}: PasswordValidatorProps) => {
  const testResults = rules.map((rule) => Boolean(rule.test(password, confirmPassword)));

  useEffect(() => {
    if (!onTestsPassed) {
      return;
    }
    onTestsPassed(testResults.every((value) => value));
  }, [password, confirmPassword, rules]);

  return (
    <StyledPasswordValidator>
      {rules.map((rule, index) => (
        <PasswordRule isPassed={testResults[index]} key={rule.label}>
          <PasswordIcon>
            <Check
              color={rule.test(password, confirmPassword)
                ? COLOR.SUCCESS : COLOR.GRAY}
              size={SIZE.SMALL}
            />
          </PasswordIcon>

          {rule.label}
        </PasswordRule>
      ))}
    </StyledPasswordValidator>
  );
};

export default PasswordValidator;
