<script setup>
import { ref } from "vue";
import { useQuasar, useDialogPluginComponent } from "quasar";
import { getApiClient } from "@hostlink/light";
const api = getApiClient();
import { useI18n } from "vue-i18n";
const { t } = useI18n();
const $q = useQuasar();
const { dialogRef, onDialogHide, onDialogOK, onDialogCancel } = useDialogPluginComponent();
const username = ref("");
const email = ref("");
const onOKClick = async () => {
  if (username.value == "" || email.value == "") {
    $q.notify({
      type: "negative",
      message: t("Username and Email is required")
    });
    return;
  }
  try {
    $q.loading.show();
    const jwt = await api.auth.forgetPassword(username.value, email.value);
    onDialogOK({
      jwt
    });
  } catch (e) {
    $q.notify({
      type: "negative",
      message: e.message
    });
    onDialogCancel();
  } finally {
    $q.loading.hide();
  }
};
</script>

<template>
    <q-dialog ref="dialogRef">
        <q-card class="q-dialog-plugin">

            <q-card-section class="q-dialog__title">
                {{ t('Forget password') }}
            </q-card-section>

            <q-card-section class="q-dialog__message">
                {{ t('Please enter your username and email address, we will send you a code to reset your password') }}
            </q-card-section>

            <q-card-section>
                <q-input v-model="username" :label="$t('Username')" stack-label
                    :rules="[val => !!val || $t('Username is required')]" hide-bottom-space />
                <q-input v-model="email" :label="$t('Email')" stack-label type="email" hide-bottom-space :rules="[
                    val => !!val || $t('Email is required'),
                    val => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(val) || $t('Invalid email format')
                ]" />
            </q-card-section>

            <q-card-actions align="right">
                <q-btn :label="$t('Cancel')" @click="onDialogCancel" flat color="primary" />
                <q-btn :label="$t('OK')" @click="onOKClick" flat color="primary" />
            </q-card-actions>
        </q-card>
    </q-dialog>
</template>
