<script setup>

import { useI18n } from 'vue-i18n';
const i18n = useI18n();
const t = i18n.t;

import { ref, useTemplateRef } from 'vue';
import { Dialog, TextInput, ClipboardButton, FormGroup, Button, InputGroup } from '@cloudron/pankow';
import UsersModel from '../models/UsersModel.js';

const usersModel = UsersModel.create();

const dialog = useTemplateRef('dialog');
const user = ref({});
const formError = ref('');
const email = ref('');
const resetLink = ref('');
const busy = ref(false);

async function onSend() {
  busy.value = true;

  const [error] = await usersModel.sendPasswordResetEmail(user.value.id, email.value);
  if (error) {
    busy.value = false;
    formError.value = error.body ? error.body.message : 'Internal error';
    return console.error(error);
  }

  window.pankow.notify({ type: 'success', text: t('profile.passwordResetNotification.body', { email: email.value }) });
  busy.value = false;

  dialog.value.close();
}

defineExpose({
  async open(u) {
    u = JSON.parse(JSON.stringify(u)); // make a copy
    user.value = u;
    formError.value = '';
    email.value = u.fallbackEmail || u.email;

    const [error, result] = await usersModel.getPasswordResetLink(u.id);
    if (error) return console.error(error);
    resetLink.value = result;

    dialog.value.open();
  }
});

</script>

<template>
  <Dialog ref="dialog"
    :title="$t('users.passwordResetDialog.title', { username: (user.username || user.email) })"
    :reject-label="$t('main.dialog.close')"
  >
    <FormGroup>
      <label class="control-label">{{ $t('users.passwordResetDialog.descriptionLink') }}</label>
      <InputGroup>
        <TextInput id="passwordResetLinkInput" style="flex-grow: 1;" v-model="resetLink" readonly/>
        <ClipboardButton :value="resetLink" />
      </InputGroup>
    </FormGroup>

    <br/>

    <p class="text-danger" v-show="formError">{{ formError }}</p>
    <form @submit.prevent="onSend()">
      <fieldset :disabled="busy">
        <input type="submit" style="display: none" />

        <FormGroup>
          <label for="emailInput">{{ $t('users.passwordResetDialog.descriptionEmail') }}</label>
          <InputGroup>
            <TextInput id="emailInput" style="flex-grow: 1;" v-model="email" :disabled="busy" />
            <Button @click="onSend()" :disabled="busy" :loading="busy">{{ $t('users.passwordResetDialog.sendAction') }}</Button>
          </InputGroup>
        </FormGroup>
      </fieldset>
    </form>

  </Dialog>
</template>
