<script setup>

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

import { ref, onMounted, onUnmounted, useTemplateRef } from 'vue';
import { Button, ProgressBar, InputDialog } from '@cloudron/pankow';
import { prettyLongDate } from '@cloudron/pankow/utils';
import Section from '../components/Section.vue';
import SettingsItem from '../components/SettingsItem.vue';
import AppstoreModel from '../models/AppstoreModel.js';
import DashboardModel from '../models/DashboardModel.js';

const appstoreModel = AppstoreModel.create();
const dashboardModel = DashboardModel.create();

const consoleServerOrigin = ref();
const busy = ref(true);
const hasSubscription = ref(false);
const email = ref('');
const emailEncoded = ref('');
const emailVerified = ref(false);
const cloudronId = ref('');
const planId = ref('');
const planName = ref('');
const cancelAt = ref(0);
const status = ref('');

let pollTimeoutId = 0;

async function refresh() {
  const [error, result] = await appstoreModel.getSubscription();
  if (error) {
    if (error.status === 402) return busy.value = false;  // not yet registered
    if (error.status === 412) return busy.value = false;  // invalid appstore token
    return console.error(error);
  }

  hasSubscription.value = true;
  email.value = result.email;
  emailEncoded.value = encodeURIComponent(result.email);;
  emailVerified.value = result.emailVerified;
  cloudronId.value = result.cloudronId;
  planId.value = result.plan.id;
  planName.value = result.plan.name;
  cancelAt.value = result.cancel_at;
  status.value = result.status;
}

const inputDialog = useTemplateRef('inputDialog');
async function onAskUnlinkAccount() {
  const yes = await inputDialog.value.confirm({
    title: t('settings.appstoreAccount.unlinkDialog.title'),
    message: t('settings.appstoreAccount.unlinkDialog.description'),
    confirmStyle: 'danger',
    confirmLabel: t('main.dialog.yes'),
    rejectLabel: t('main.dialog.cancel'),
    rejectStyle: 'secondary',
  });

  if (!yes) return;

  await onUnlinkAccount();
}

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

  const [error] = await appstoreModel.unlinkAccount();
  if (error) return console.error(error);

  await refresh();

  busy.value = false;
}

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

  consoleServerOrigin.value = result.consoleServerOrigin;

  await refresh();
  busy.value = false;

  pollTimeoutId = setInterval(refresh, 3000);
});

onUnmounted(() => {
  clearInterval(pollTimeoutId);
});

</script>

<template>
  <div class="content">
    <InputDialog ref="inputDialog"/>

    <Section :title="$t('settings.appstoreAccount.title')">
      <!-- TODO: Show plan info -->

      <div v-if="!busy">
        <div v-if="hasSubscription">
          <div>{{ $t('settings.appstoreAccount.description') }}</div>
          <br/>

          <div class="info-row">
            <div class="info-label">{{ $t('settings.appstoreAccount.account') }}</div>
            <!-- TODO button is a link to console.cloudron.io/setup-subscription?cloudronId=xxx -->
            <div v-if="email" class="info-value"><a :href="`${consoleServerOrigin}?email=${emailEncoded}`" target="_blank">{{ email }} <i v-show="!emailVerified" class="fas fa-exclamation-triangle text-danger" v-tooltip="$t('settings.appstoreAccount.emailNotVerified')"></i></a></div>
            <div v-else class="info-value">None</div>
          </div>

          <div class="info-row">
            <div class="info-label">{{ $t('settings.appstoreAccount.cloudronId') }}</div>
            <div class="info-value">{{ cloudronId }}</div>
          </div>

          <div class="info-row">
            <div class="info-label">{{ $t('settings.appstoreAccount.subscription') }} <span v-if="cancelAt" class="error-label">{{ $t('settings.appstoreAccount.subscriptionEndsAt') }} {{ prettyLongDate(cancelAt*1000) }}</span></div>
            <div class="info-value">{{ planName }}</div>
          </div>

          <div class="button-bar" style="margin-top: 20px">
            <Button :href="`${consoleServerOrigin}/#/claim/${cloudronId}`" target="_blank">
              <span v-if="!email">{{ $t('settings.appstoreAccount.setupAction') }}</span>
              <span v-else-if="cancelAt">{{ $t('settings.appstoreAccount.subscriptionReactivateAction') }}</span>
              <span v-else>{{ $t('settings.appstoreAccount.subscriptionChangeAction') }}</span>
            </Button>

            <Button secondary @click="onAskUnlinkAccount" v-if="email">{{ $t('settings.appstoreAccount.unlinkAction') }}</Button>
          </div>
        </div>

        <SettingsItem v-else-if="cloudronId">
          <div style="display: flex; align-items: center;">
            {{ $t('settings.appstoreAccount.description') }}
          </div>
          <div style="display: flex; align-items: center;">
            <Button :href="`${consoleServerOrigin}/#/claim/${cloudronId}`" target="_blank">{{ $t('settings.appstoreAccount.setupAction') }}</Button>
          </div>
        </SettingsItem>

        <SettingsItem v-else>
          <div style="display: flex; align-items: center;">
            Unknown Cloudron ID or invalid cloudron.io token.
          </div>
          <div style="display: flex; align-items: center;">
            <Button @click="onUnlinkAccount">{{ $t('settings.appstoreAccount.unlinkAction') }}</Button>
          </div>
        </SettingsItem>
      </div>
      <div v-else>
        <ProgressBar mode="indeterminate" slim :show-label="false"/>
      </div>
    </Section>
  </div>
</template>
