<script setup>

import { ref, useTemplateRef, computed } 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 isFormValid = computed(() => {
  if (email.value && !isValidEmail(email.value)) return false;
  if (!password.value) return false;

  return true;
});

async function onSubmit() {
  if (!isFormValid.value) 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();
  }
});

</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">
      <fieldset :disabled="busy">
        <input type="submit" style="display: none;" :disabled="!isFormValid"/>

        <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" />
          <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" />
          <div class="error-label" v-if="formError.password">{{ formError.password }}</div>
        </FormGroup>
      </fieldset>
    </form>
  </Dialog>
</template>
