<script setup>

import { ref, useTemplateRef } from 'vue';
import { EmailInput, PasswordInput, Dialog, FormGroup } from '@cloudron/pankow';
import { isValidEmail } from '@cloudron/pankow/utils';
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 email = ref('');
const password = ref('');

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

  if (isFormValid.value) {
    if (!isValidEmail(email.value)) isFormValid.value = false;
  }
}

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

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

  const [error] = await profileModel.setFallbackEmail(email.value, password.value);
  if (error) {
    if (error.status === 400) formError.value.email = error.body.message;
    else if (error.status === 412) formError.value.password = error.body.message;
    else {
      formError.value.generic = error.status ? error.body.message : 'Internal error';
      console.error('Failed to set fallback email', error);
    }

    busy.value = false;

    return;
  }

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

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

defineExpose({
  async open(e) {
    email.value = e;
    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="$t('profile.changeFallbackEmail.title')"
    :confirm-label="$t('main.dialog.save')"
    :confirm-active="!busy && isFormValid"
    :confirm-busy="busy"
     confirm-style="primary"
    :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.email">
          <label>{{ $t('profile.changeEmail.email') }}</label>
          <EmailInput v-model="email" required/>
          <div class="error-label" v-if="formError.email">{{ formError.email }}</div>
        </FormGroup>

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