<template>
  <q-dialog ref="dialogRef" persistent @hide="onDialogHide">
    <q-card class="q-dialog-plugin overflow-hidden" style="min-width: 400px">
      <DefaultDialogHeader title="Acesso ao Financeiro" @close="onCancel" />

      <q-card-section class="q-pt-none q-pb-sm">
        <div class="text-caption text-grey-6 q-mb-sm">
          Confirme sua senha para acessar o módulo Financeiro.
        </div>
        <q-form @submit.prevent="onConfirm">
          <q-input
            ref="passwordInput"
            v-model="password"
            type="password"
            outlined
            dense
            autofocus
            label="Senha"
            :error="hasError"
            :error-message="errorMessage"
            @update:model-value="hasError = false"
          >
            <template #prepend>
              <q-icon name="mdi-lock-outline" />
            </template>
          </q-input>
        </q-form>
      </q-card-section>

      <q-card-actions align="right">
        <q-btn outline color="primary" label="Cancelar" :disable="loading" @click="onCancel" />
        <q-btn
          color="primary"
          label="Confirmar"
          :loading="loading"
          :disable="!password"
          @click="onConfirm"
        />
      </q-card-actions>
    </q-card>
  </q-dialog>
</template>

<script setup>
import { ref } from "vue";
import { useDialogPluginComponent } from "quasar";
import DefaultDialogHeader from "src/components/defaults/DefaultDialogHeader.vue";
import { confirmPassword } from "src/api/auth";

defineEmits([...useDialogPluginComponent.emits]);

const { dialogRef, onDialogHide, onDialogOK, onDialogCancel } = useDialogPluginComponent();

const password = ref("");
const loading = ref(false);
const hasError = ref(false);
const errorMessage = ref("");

async function onConfirm() {
  if (!password.value || loading.value) return;
  loading.value = true;
  hasError.value = false;
  try {
    await confirmPassword(password.value);
    onDialogOK();
  } catch (error) {
    hasError.value = true;
    errorMessage.value =
      error?.response?.data?.message || "A senha fornecida está incorreta.";
  } finally {
    loading.value = false;
  }
}

function onCancel() {
  onDialogCancel();
}
</script>
