<script setup>

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

import { ref, onMounted, onUnmounted, useTemplateRef, computed, inject } from 'vue';
import { Button, ProgressBar, InputDialog, ClipboardAction } from '@cloudron/pankow';
import { prettyLongDate } from '@cloudron/pankow/utils';
import Section from '../components/Section.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 email = ref('');
const emailEncoded = ref('');
const emailVerified = ref(false);
const cloudronId = ref('');
const planId = ref('');
const planName = ref('');
const cancelAt = ref(0);
const renewsAt = ref(0);
const status = ref('');

const refreshFeatures = inject('refreshFeatures');

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);
  }

  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;
  renewsAt.value = result.current_period_end;
  status.value = result.status;

  await refreshFeatures();
}

const appstoreCloudronLink = computed(() => {
  return `${consoleServerOrigin.value}/#/${email.value ? 'cloudron' : 'claim'}/${cloudronId.value}`;
});

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('settings.appstoreAccount.unlinkAction'),
    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="cloudronId">
          <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 }}
              <ClipboardAction plain :value="cloudronId"/>
            </div>
          </div>

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

          <div class="info-row" v-if="planId !== 'free'">
            <div class="info-label">Status</div>
            <div class="info-value">
              <span v-if="cancelAt"><b class="text-danger">Canceled</b> (Ends on {{ prettyLongDate(cancelAt*1000) }})</span>
              <span v-else-if="status === 'canceled'"><b class="text-danger">Canceled</b></span>
              <span v-else-if="status === 'past_due' || status === 'incomplete_expired'"><b class="text-danger">Expired</b></span>
              <span v-else><b class="text-success">Active</b> (Renews on {{  prettyLongDate(renewsAt*1000) }})</span>
            </div>
          </div>

          <div class="button-bar" style="margin-top: 20px">
            <Button :href="appstoreCloudronLink" 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>

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