<script setup>
import { useDialogPluginComponent } from "quasar";
import { onMounted, q, m } from "#imports";
import { ref } from "vue";
import { useQuasar } from "quasar";
const $q = useQuasar();
const props = defineProps({
  username: {
    type: String,
    required: true
  },
  password: {
    type: String,
    required: true
  }
});
const secret = ref("");
const code = ref("");
defineEmits([
  // REQUIRED; need to specify some events that your
  // component will emit through useDialogPluginComponent()
  ...useDialogPluginComponent.emits
]);
const { dialogRef, onDialogHide, onDialogOK, onDialogCancel } = useDialogPluginComponent();
function onOKClick() {
  m("updateTwoFactorAuthentication", {
    username: props.username,
    password: props.password,
    secret: secret.value,
    code: code.value
  }).then(() => {
    $q.notify({
      type: "positive",
      message: "Two-factor authentication has been successfully set up. Please use your authenticator app to log in."
    });
    onDialogOK();
  }).catch((error) => {
    $q.notify({
      type: "negative",
      message: error.message || "Failed to update two-factor authentication."
    });
  });
}
const image = ref("");
onMounted(async () => {
  const { app } = await q({
    app: {
      generate2FASecret: {
        __args: {
          username: props.username
        }
      }
    }
  });
  image.value = app.generate2FASecret.image;
  secret.value = app.generate2FASecret.secret;
});
</script>

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

            <q-card-section>
                <div class="text-h6">Setup Two Factor Authentication</div>
                <div>
                    To enhance the security of your account, please set up two-factor authentication (2FA) using an
                    authenticator app such as Google Authenticator or Microsoft Authenticator. Scan the QR code below
                    with your chosen app
                    to link it to your account.
                </div>

                <div class="q-mt-md q-mb-md flex flex-center" v-if="image">
                    <img :src="image" alt="2FA QR Code" />
                </div>

                <div>
                    <q-input label="Enter the 6-digit code from your authenticator app" type="text" v-model="code"
                        clearable stackLabel :outlined="false">
                        <template v-slot:prepend>
                            <q-icon name="sym_o_key" />
                        </template>
                    </q-input>
                </div>

            </q-card-section>

            <q-card-actions align="right">
                <q-btn color="primary" label="OK" @click="onOKClick" />
                <q-btn color="primary" label="Cancel" @click="onDialogCancel" />
            </q-card-actions>
        </q-card>
    </q-dialog>
</template>
