<template>
  <v-row v-if="!successForgotPassword" :class="variantButton ? 'w-100' : 'w-75'" class="mx-auto" tag="form"
         @submit.prevent="onSubmit($v)">
    <v-col cols="12">
      <v-text-field
          v-model.trim="form.email"
          :error="$v.form.email.$dirty && $v.form.email.$error"
          :error-messages="getErrors($v.form.email)"
          :variant="variantButton ? undefined : 'outlined'"
          hide-details="auto"
          label="Email"
          placeholder="Email*"
          required
          type="email"
          @blur="$v.form.email.$touch()"
      ></v-text-field>

      <v-alert v-if="errorMessage" class="my-4" type="error">
        {{ errorMessage }}
      </v-alert>
    </v-col>

    <v-col class="text-end" cols="12">
      <v-btn
          :loading="loading"
          :variant="variantButton ? undefined : 'elevated'"
          color="primary"
          height="50"
          type="submit"
      >
        Submit
      </v-btn>
    </v-col>
  </v-row>

  <div v-else>
    <v-icon
        class="check-congratulations text-green-darken-3 w-100 mb-5"
        icon="mdi-checkbox-marked-circle"
    />
    <h4 class="text-center mb-6 text-capitalize">
      Email sent successfully. Please check your email to finish the recovery process
    </h4>
  </div>
</template>

<script setup>
const { useVuelidate } = Vuelidate;
const { email, required } = VuelidateValidators;

const form = Vue.ref({email: ""})
const rules = {form: {email: {required, email}}}
const $v = useVuelidate(rules, {form})
const loading = Vue.ref(false)
const successForgotPassword = Vue.ref(false)
const errorMessage = Vue.ref('')
const props = defineProps({variantButton: {type: String, default: ''}})

const getErrors = ($v) => {
  if ($v.$dirty && $v.$errors?.length)
    return $v.$errors.map((e) => {
      switch (e.$validator) {
        case "sameAs":
          return "Passwords do not match"
        default:
          return e.$message
      }
    })
  else return []
}

const onSubmit = async (formSubmit) => {
  if (formSubmit.$invalid) return

  try {
    loading.value = true
    const { data } = await axios.post(
			'/account/password_recover',
			form.value,
		);
    if (data.success) successForgotPassword.value = true
  } catch (e) {
    errorMessage.value = e.response.data.message
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.check-congratulations {
  font-size: 60px;
}
</style>