<script setup>

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

import { ref, onMounted, useTemplateRef } from 'vue';
import { Button, TableView, Checkbox, InputDialog, Dialog, FormGroup, TextInput, InputGroup, Switch, ButtonGroup, SingleSelect } from 'pankow';
import Section from '../components/Section.vue';
import SettingsItem from '../components/SettingsItem.vue';
import DomainsModel from '../models/DomainsModel.js';
import MailModel from '../models/MailModel.js';
import ProfileModel from '../models/ProfileModel.js';
import TasksModel from '../models/TasksModel.js';

const domainsModel = DomainsModel.create();
const mailModel = MailModel.create();
const profileModel = ProfileModel.create();
const tasksModel = TasksModel.create();

const inputDialog = useTemplateRef('inputDialog');
const enableIncomingDialog = useTemplateRef('enableIncomingDialog');

const domain = ref('');
const domainProvider = ref('');
const mailConfig = ref({});
const refreshBusy = ref(false);
const incomingEnabled = ref(false);
const enableIncomeBusy = ref(false);
const enableIncomingSetupDns = ref(false);

async function onAskIncomingToggle(value) {
  if (value) {
    enableIncomeBusy.value = false;
    return enableIncomingDialog.value.open();
  }

  const yes = await inputDialog.value.confirm({
    title: t('email.disableEmailDialog.title', { domain: domain.value }),
    message: t('email.disableEmailDialog.description', { domain: domain.value }),
    modal: true,
    confirmStyle: 'danger',
    confirmLabel: t('email.disableEmailDialog.disableAction'),
    rejectLabel: t('main.dialog.cancel'),
    rejectStyle: 'secondary',
  });

  // reset switch
  if (!yes) return incomingEnabled.value = true;

  const [error] = await mailModel.setEnabled(domain.value, false);
  if (error) return console.error(error);

  // TODO this has to be done in the backend here! reconfigureEmailApps();

  refreshBusy.value = true;
  setTimeout(refreshMailConfig, 2000);
}

async function onEnableIncoming() {
  enableIncomeBusy.value = true;

  const [error] = await mailModel.setEnabled(domain.value, true);
  if (error) return console.error(error);

  // TODO this has to be done in the backend here! reconfigureEmailApps();

  if (enableIncomingSetupDns.value) {
    const [error] = await domainsModel.setDnsRecords({ domain: domain.value, type: 'mail' });
    if (error) console.error(error);
  }

  setTimeout(async () => {
    await refreshMailConfig();
    enableIncomingDialog.value.close();
    enableIncomeBusy.value = false;
  }, 2000);
}

async function refreshMailConfig() {

  const [error, result] = await mailModel.config(domain.value);
  if (error) return console.error(error);

  mailConfig.value = result;
  incomingEnabled.value = result.enabled;
  domainProvider.value = '';

  refreshBusy.value = false;
}

onMounted(async () => {
  domain.value = window.location.hash.slice('#/email/'.length);
  if (!domain.value) return;

  const [error, result] = await domainsModel.get(domain.value);
  if (error) return console.error(error);

  domainProvider.value = result.provider;

  await refreshMailConfig();
});

</script>

<template>
  <div>
    <InputDialog ref="inputDialog"/>
    <Dialog ref="enableIncomingDialog"
      :title="$t('email.enableEmailDialog.title', { domain: domain })"
      :confirm-label="$t('email.enableEmailDialog.enableAction')"
      :confirm-busy="enableIncomeBusy"
      :reject-label="enableIncomeBusy ? '' : $t('main.dialog.cancel')"
       reject-style="secondary"
      @confirm="onEnableIncoming()"
    >
      <div>
        <p v-html="$t('email.enableEmailDialog.description', { domain: domain, requiredPortsDocsLink: 'https://docs.cloudron.io/email/#required-ports' })"></p>
        <!-- TODO <p class="text-danger" v-if="adminDomain.provider === 'cloudflare'" v-html="$t('email.enableEmailDialog.cloudflareInfo', { adminDomain: config.adminDomain, mailFqdn: config.mailFqdn })"></p> -->
        <div v-if="domainProvider === 'noop' || domainProvider === 'manual'" v-html="$t('email.enableEmailDialog.noProviderInfo')"></div>
        <div v-else>
          <Checkbox v-model="enableIncomingSetupDns" :label="$t('email.enableEmailDialog.setupDnsCheckbox')"/>
          <div v-html="$t('email.enableEmailDialog.setupDnsInfo', { importEmailDocsLink: 'https://docs.cloudron.io/guides/import-email' })"></div>
        </div>
      </div>
    </Dialog>

    <Section :title="$t('email.config.title', { domain: domain })">

    </Section>

    <Section :title="$t('emails.settings.title')">
      <SettingsItem>
        <FormGroup>
          <label>{{ $t('email.incoming.title') }}</label>
          <div>{{ $t(mailConfig.enabled ? 'email.incoming.enabled' : 'email.incoming.disabled') }}</div>
        </FormGroup>
        <Switch v-model="incomingEnabled" :disabled="refreshBusy" @change="onAskIncomingToggle"/>
      </SettingsItem>
    </Section>
  </div>
</template>
