<script setup>

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

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

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

const usersModel = UsersModel.create();

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

async function onSendInvite() {
  const [error] = await usersModel.sendInviteEmail(user.value.id, email.value);
  if (error) return console.error(error);

  window.pankow.notify({ type: 'success', text: t('users.invitationNotification.body', { email: email.value })});

  dialog.value.close();
}

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

    dialog.value.open();

    const [error, result] = await usersModel.inviteLink(u.id);
    if (error) {
      if (error.status === 409) {
        emit('refreshRequired');
        dialog.value.close();
      } else {
        console.error(error);
      }

      return;
    }
    inviteLink.value = result;
  }
});

</script>

<template>
  <Dialog ref="dialog"
    :title="$t('users.invitationDialog.title', { username: user? (user.username || user.email) : '' })"
    :reject-label="$t('main.dialog.close')"
     reject-style="secondary"
  >
    <div>
      <div v-if="!inviteLink" style="text-align: center;">
        <ProgressBar mode="indeterminate" :show-label="false" :slim="true"/>
      </div>
      <div v-else>
        <FormGroup>
          <label>{{ $t('users.invitationDialog.descriptionLink') }}</label>
          <InputGroup>
            <TextInput style="flex-grow: 1;" v-model="inviteLink" readonly/>
            <ClipboardButton :value="inviteLink" />
          </InputGroup>
        </FormGroup>

        <FormGroup>
          <label>{{ $t('users.invitationDialog.descriptionEmail') }}</label>
          <InputGroup>
            <EmailInput style="flex-grow: 1;" v-model="email"/>
            <Button @click="onSendInvite()" :loading="busy">{{ $t('users.invitationDialog.sendAction') }}</Button>
          </InputGroup>
        </FormGroup>
      </div>
    </div>
  </Dialog>
</template>
