<script setup>

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

import { ref, onMounted, useTemplateRef, computed, inject } from 'vue';
import { Button, TableView, TextInput, InputDialog, ProgressBar } from '@cloudron/pankow';
import Certificates from '../components/Certificates.vue';
import ActionBar from '../components/ActionBar.vue';
import SyncDns from '../components/SyncDns.vue';
import DomainDialog from '../components/DomainDialog.vue';
import DashboardDomain from '../components/DashboardDomain.vue';
import WellKnownDialog from '../components/WellKnownDialog.vue';
import Section from '../components/Section.vue';
import DashboardModel from '../models/DashboardModel.js';
import DomainsModel from '../models/DomainsModel.js';

const dashboardModel = DashboardModel.create();
const domainsModel = DomainsModel.create();

const busy = ref(false);
const domains = ref([]);
const search = ref('');
const dashboardDomain = ref('');
const domainDialog = useTemplateRef('domainDialog');
const wellKnownDialog = useTemplateRef('wellKnownDialog');
const dashboardDomainComponent = useTemplateRef('dashboardDomainComponent');

const features = inject('features');
const subscriptionRequiredDialog = inject('subscriptionRequiredDialog');

function onAdd () {
  if (features.value.domainMaxCount <= domains.value.length) subscriptionRequiredDialog.value.open();
  else domainDialog.value.open(null);
}

function onEdit(domain) {
  domainDialog.value.open(domain); // pass a copy to prevent the dialog from mutating
}

const inputDialog = useTemplateRef('inputDialog');

async function onRemove(domain) {
  const yes = await inputDialog.value.confirm({
    title: t('domains.removeDialog.title'),
    message: t('domains.removeDialog.description', { domain: domain.domain }),
    confirmStyle: 'danger',
    confirmLabel: t('domains.removeDialog.removeAction'),
    rejectLabel: t('main.dialog.cancel'),
    rejectStyle: 'secondary'
  });

  if (!yes) return;

  const [error] = await domainsModel.remove(domain.domain);
  if (error) {
    if (error.status === 409) window.pankow.notify({ text: error.body.message || `Domain is still in use.`, type: 'danger', persistent: true });
    return console.error(error);
  }

  await refreshDomains();
}

const columns = ref({
  domain: {
    label: t('domains.domain'),
    sort: true
  },
  provider: {
    label: t('domains.provider'),
    sort: true,
    hideMobile: true,
  },
  actions: {
    width: '100px',
  }
});

function createActionMenu(domain) {
  return [{
    icon: 'fa-solid fa-pencil-alt',
    label: t('main.action.edit'),
    quickAction: true,
    action: onEdit.bind(null, domain),
  },{
    separator: true,
  }, {
    icon: 'fa-solid fa-atlas',
    label: t('domains.wellknown.editAction'),
    action: () => wellKnownDialog.value.open(domain),
  }, {
    separator: true,
  }, {
    icon: 'fa-solid fa-trash-alt',
    label: t('main.action.remove'),
    disabled: domain.domain === dashboardDomain.value,
    action: onRemove.bind(null, domain),
  }];
}

const filteredDomains = computed(() => {
  if (!search.value) return domains.value;

  return domains.value.filter(d => {
    return d.domain.indexOf(search.value) !== -1 || d.provider.indexOf(search.value) !== -1;
  });
});

async function refreshDomains() {
  const [error, result] = await domainsModel.list();
  if (error) return console.error(error);

  domains.value = result;

  dashboardDomainComponent.value?.updateDomains(result);
}

onMounted(async () => {
  busy.value = true;
  await refreshDomains();

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

  dashboardDomain.value = result.adminDomain;
  busy.value = false;
});

</script>

<template>
  <div class="content">
    <InputDialog ref="inputDialog" />
    <DomainDialog ref="domainDialog" @success="refreshDomains()"/>
    <WellKnownDialog ref="wellKnownDialog" @success="refreshDomains()"/>

    <Section :title="$t('domains.title')">
      <template #header-title-extra>
        <span style="font-weight: normal; font-size: 14px">({{ busy ? '-' : filteredDomains.length }})</span>
      </template>
      <template #filter-bar>
        <TextInput v-model="search" :placeholder="$t('main.searchPlaceholder')" style="flex-grow: 1;"/>
      </template>
      <template #header-buttons>
        <Button @click="onAdd()">{{ $t('main.action.add') }}</Button>
      </template>

      <div>{{ $t('domains.description') }}</div>

      <br/>

      <ProgressBar v-if="busy" mode="indeterminate" :show-label="false" :slim="true" :show-track="false"/>

      <TableView :model="filteredDomains" :columns="columns" :busy="busy" style="max-height: 450px;" :placeholder="$t(search ? 'domains.noMatchesPlaceholder' : 'domains.emptyPlaceholder')">
        <template #provider="{ item:domain }">
          {{ DomainsModel.prettyProviderName(domain.provider) }}
        </template>
        <template #actions="{ item:domain }">
          <ActionBar :actions="createActionMenu(domain)" />
        </template>
      </TableView>
    </Section>

    <Certificates />
    <SyncDns />
    <DashboardDomain ref="dashboardDomainComponent"/>
  </div>
</template>
