<script setup>

import { ref, useTemplateRef } from 'vue';
import { PasswordInput, Dialog, FormGroup } from '@cloudron/pankow';
import ProfileModel from '../models/ProfileModel.js';

const emit = defineEmits([ 'success' ]);

const profileModel = ProfileModel.create();

const dialog = useTemplateRef('dialog');
const formError = ref({});
const busy = ref (false);
const password = ref('');
const twoFAMethod = ref('totp'); // 'totp' or 'passkey'

const form = useTemplateRef('form');
const isFormValid = ref(false);
function checkValidity() {
  isFormValid.value = form.value ? form.value.checkValidity() : false;
}

async function onSubmit() {
  if (!form.value.reportValidity()) return;

  busy.value = true;
  formError.value = {};

  let error;
  if (twoFAMethod.value === 'passkey') {
    [error] = await profileModel.deletePasskey(password.value);
  } else {
    [error] = await profileModel.disableTwoFA(password.value);
  }

  if (error) {
    if (error.status === 412) {
      password.value = '';
      formError.value.password = error.body.message;
      setTimeout(() => document.getElementById('passwordInput')?.focus(), 0);
    } else {
      formError.value.generic = error.status ? error.body.message : 'Internal error';
      console.error('Failed to disable 2fa', error);
    }

    busy.value = false;

    return;
  }

  emit('success');
  dialog.value.close();

  busy.value = false;
  formError.value = {};
}

defineExpose({
  async open(method = 'totp') {
    twoFAMethod.value = method;
    password.value = '';
    busy.value = false;
    formError.value = {};
    dialog.value.open();

    setTimeout(checkValidity, 100); // update state of the confirm button
  }
});

</script>

<template>
  <Dialog ref="dialog"
    :title="twoFAMethod === 'totp' ? $t('profile.disableTotp.title') : $t('profile.disablePasskey.title')"
    :confirm-label="$t('profile.disable2FA.disable')"
    :confirm-active="!busy && isFormValid"
    :confirm-busy="busy"
     confirm-style="danger"
    :reject-label="$t('main.dialog.cancel')"
    :reject-active="!busy"
     reject-style="secondary"
     @confirm="onSubmit"
  >
    <form @submit.prevent="onSubmit" autocomplete="off" ref="form"  @input="checkValidity()">
      <fieldset :disabled="busy">
        <input type="submit" style="display: none;">

        <div class="error-label" v-if="formError.generic">{{ formError.generic }}</div>

        <FormGroup :has-error="formError.password">
          <label>{{ $t('profile.disable2FA.password') }}</label>
          <PasswordInput v-model="password" required id="passwordInput" />
          <div class="error-label" v-if="formError.password">{{ formError.password }}</div>
        </FormGroup>
      </fieldset>
    </form>
  </Dialog>
</template>
