<template>
  <div>
    <input
      autocomplete="false"
      name="hidden"
      type="text"
      style="display: none"
    />
    <v-text-field
      v-model="newPassword"
      class="mt-6"
      autocomplete="off"
      :rules="[
        () =>
          !newPassword.length ||
          passwordStrength.score >= minStrength ||
          'Esta senha é muito simples!'
      ]"
      :type="show ? 'text' : 'password'"
      outlined
      name="new-password"
      label="Nova senha"
      :hint="strengthTips ? passwordStrength.message : ''"
      :append-icon="show ? 'mdi-eye-outline' : 'mdi-eye-off-outline'"
      validate-on-blur
      @click:append="show = !show"
      @keyup="onInput"
    />

    <v-expand-transition>
      <PasswordStrengthMeter
        v-if="newPassword && strengthTips"
        :password-strength="passwordStrength.score"
      />
    </v-expand-transition>

    <v-expand-transition>
      <v-text-field
        v-show="!show"
        v-model="passwordConfirmation"
        autocomplete="off"
        :rules="[
          () =>
            newPassword === passwordConfirmation || 'As senhas não coincidem.'
        ]"
        class="mt-6"
        type="password"
        outlined
        name="passwordConfirmation"
        label="Confirme a nova senha"
        validate-on-blur
        @keyup="onInput"
      />
    </v-expand-transition>
  </div>
</template>

<script>
import PasswordStrengthMeter from './PasswordStrengthMeter'
import { passwordStrengthEvaluator } from '../utils/passwordStrengthEvaluator'

export default {
  name: 'NewPasswordFields',
  components: {
    PasswordStrengthMeter
  },
  props: {
    suggestion: {
      type: String,
      default: ''
    }
  },
  data: () => ({
    newPassword: '',
    passwordConfirmation: '',
    show: false,
    minStrength: 2,
    strengthTips: true
  }),
  computed: {
    passwordStrength() {
      return passwordStrengthEvaluator(this.newPassword)
    }
  },
  watch: {
    show() {
      this.onInput()
    },
    suggestion(v) {
      this.strengthTips = false
      this.newPassword = v
      this.show = true
      this.$emit('input', this.newPassword)
    }
  },
  mounted() {
    this.newPassword = this.suggestion
  },
  methods: {
    onInput() {
      this.strengthTips = true

      if (
        (this.show || this.newPassword === this.passwordConfirmation) &&
        this.passwordStrength.score >= this.minStrength
      )
        this.$emit('input', this.newPassword)
      else this.$emit('input', '')
    }
  }
}
</script>
