<script setup>

import { computed, ref, useTemplateRef, inject } from 'vue';
import { Dialog, TextInput, FormGroup, Checkbox, InputGroup, SingleSelect } from '@cloudron/pankow';
import MailinglistsModel from '../models/MailinglistsModel.js';

const emit = defineEmits([ 'success' ]);
const props = defineProps([ 'domains' ]);

const mailinglistsModel = MailinglistsModel.create();

const dialog = useTemplateRef('dialog');
const busy = ref(false);
const formError = ref({});
const name = ref('');
const domain = ref('');
const mailinglist = ref(null);
const membersText = ref('');
const membersOnly = ref(false);
const active = ref(true);
const domainList = ref([]);
const dashboardDomain = inject('dashboardDomain');

const memberCount = computed(() => {
  return membersText.value.split('\n').map(m => m.trim()).filter(m => m).length;
});

async function onSubmit() {
  busy.value = true;
  formError.value = {};

  const data = {
    members: membersText.value.split('\n').map(m => m.trim()).filter(m => m),
    membersOnly: membersOnly.value,
    active: active.value,
  };

  if (mailinglist.value) {
    const [error] = await mailinglistsModel.update(domain.value, name.value, data);
    if (error) {
      busy.value = false;
      if (error.status === 400 && error.body.message.indexOf('Invalid mail member') === 0) formError.value.members = error.body.message;
      else if (error.status === 400) formError.value.name = error.body.message;
      else formError.value.generic = error.body ? error.body.message : 'Internal error';
      return console.error(error);
    }
  } else {
    const [error] = await mailinglistsModel.add(domain.value, name.value, data);
    if (error) {
      busy.value = false;
      if (error.status === 400 && error.body.message.indexOf('Invalid mail member') === 0) formError.value.members = error.body.message;
      else if (error.status === 400) formError.value.name = error.body.message;
      else formError.value.generic = error.body ? error.body.message : 'Internal error';
      return console.error(error);
    }
  }

  emit('success');
  dialog.value.close();
  busy.value = false;
}

defineExpose({
  async open(m = null) {
    m = m ? JSON.parse(JSON.stringify(m)) : null; // make a copy
    busy.value = false;
    formError.value = {};
    mailinglist.value = m;

    name.value = m ? m.name : '';
    domain.value = m ? m.domain : dashboardDomain.value;
    membersText.value = m ? m.members.join('\n') : '';
    membersOnly.value = m ? m.membersOnly : false;
    active.value = m ? m.active : true;

    domainList.value = props.domains.map(d => {
      return {
        domain: d.domain,
        label: '@' + d.domain,
      };
    });

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

</script>

<template>
  <Dialog ref="dialog"
    :title="mailinglist ? $t('email.editMailinglistDialog.title') : $t('email.addMailinglistDialog.title')"
    :style="{ 'min-width': '700px' }"
    :confirm-label="$t(mailinglist ? 'main.dialog.save' : 'email.incoming.mailboxes.addAction')"
    :confirm-busy="busy"
    :confirm-active="!busy && name !== '' && domain !== '' && membersText !== ''"
     reject-style="secondary"
    :reject-label="$t('main.dialog.cancel')"
    :reject-active="!busy"
    @confirm="onSubmit()"
  >
    <div>
      <div class="error-label" v-if="formError.generic">{{ formError.generic }}</div>

      <form @submit.prevent="onSubmit()" novalidate autocomplete="off">
         <fieldset :disabled="busy">
          <input type="submit" style="display: none;" :disabled="!name || !domain"/>

          <FormGroup>
            <label for="nameInput">{{ $t('email.addMailinglistDialog.name') }}</label>
            <InputGroup>
              <TextInput id="nameInput" style="flex-grow: 1;" v-model="name" :readonly="!!mailinglist"/>
              <SingleSelect v-model="domain" :options="domainList" option-key="domain" option-label="label" :disabled="!!mailinglist"/>
            </InputGroup>
            <div class="error-label" v-if="formError.name">{{ formError.name }}</div>
          </FormGroup>

          <FormGroup>
            <label for="membersInput">{{ $t('email.addMailinglistDialog.members') }} ({{ memberCount }})</label>
            <textarea id="membersInput" v-model="membersText" rows="5"></textarea>
            <div class="error-label" v-if="formError.members">{{ formError.members }}</div>
          </FormGroup>

          <Checkbox v-model="membersOnly" :label="$t('email.addMailinglistDialog.membersOnlyCheckbox')"/>
          <Checkbox v-model="active" v-if="mailinglist" :label="$t('email.updateMailinglistDialog.activeCheckbox')"/>
        </fieldset>
      </form>
    </div>
  </Dialog>
</template>