<template>
  <pn-page-template>
    <template #title>
      {{$t('subscribe__title')}}
    </template>

    <template #card-header>
      <div
        v-if="tariffs && currentTariff"
        id="subscribe-current-balance"
        class="flex w100 q-px-md q-py-md row bg-grey-11"
        >

        <div class="flex w100 justify-between items-center no-wrap">
          <div class="flex items-center text-grey text-caption">
            {{ $t('subscribe__current_tariff_title') }}
          </div>

          <div class="flex items-center column text-right">
            <span class="text-bold">
              {{ currentTariff?.tariffInfo.name }}
            </span>
          </div>
        </div>
        <div
          class="row w100 no-wrap items-center text-caption justify-between"
          v-if="!isCurrentTariffTest"
          >
          <div class="text-grey text-no-wrap ellipsis">
            {{ $t('subscribe__current_tariff_date') }}
          </div>
          <span class="text-no-wrap text-right" v-if="currentTariff.end_date">
            {{ date.formatDate(currentTariff.end_date * 1000, 'DD.MM.YYYY') }}
          </span>
        </div>

        <div class="row w100 no-wrap items-center text-caption text-grey justify-between">
          <div>
            {{ $t('subscribe__current_tariff_chat_limit') }}
          </div>
          <div class="text-right">
            <span
              class="text-bold q-pr-xs"
              :class="currentTariff.tariffInfo.chat_limit && (currentTariff.tariffInfo.chat_limit > currentTariff?.used_chats) ? 'negative' : ''"
              >
              {{ currentTariff.used_chats }}
            </span>
            <span v-if="currentTariff.tariffInfo.chat_limit">
              /{{ currentTariff.tariffInfo.chat_limit }}
            </span>
          </div>
        </div>
      </div>
    </template>
  
    <div v-if="tariffs && currentTariff" class="q-pt-sm">
      <subscribe-upgrade
        v-if="isCurrentTariffTest"
        :tariffs
        :periods
        @tariff-upgrade="prepareTgBtn"
      />

      <subscribe-change-renew
        v-else
        :tariffs
        :periods
        :currentTariff
        @update="prepareTgBtn"
      />

      <div class="q-pa-md">
        <q-btn
          flat
          no-caps
          rounded
          class="text-caption text-grey-10 w100"
          @click="showDialogCorp = !showDialogCorp"
          >
          {{  $t('subscribe_corp_dialog__btn') }}
        </q-btn>
      </div>
      <div
        v-if="tariffs.length === 1 && currentTariff.tariffInfo.name === 'FREE'"
        class="q-mt-md"
        >
        <q-banner class="bg-warning text-grey-9">
          <template #avatar>
            <q-icon name="mdi-alert-circle-outline"/>
          </template>
            <div class="text-weight-bold">{{ $t('subscribe__test_warning') }}</div>
            <div class="text-caption">{{ $t('subscribe__test_warning_description') }}</div>
        </q-banner>
      </div>
    </div>
    
    <pn-bottom-sheet-dialog
      v-model="showDialogCorp"
      title="subscribe_corp_dialog__title"
      >
      <div style="white-space: pre-line" class="q-px-md">
        {{  $t('subscribe_corp_dialog__sale_contact') }}
        <span
          class="text-primary text-no-wrap cursor-pointer" 
          @click="copyClick(saleEmail)"
          >
          {{ saleEmail }}
        </span>.
        <span v-if="customerTid">
          {{ $t('subscribe_corp_dialog__tid') }}
          <span
            class="text-primary text-no-wrap cursor-pointer"
            @click="copyClick(customerTid)"
            >
            {{ customerTid }}
          </span>.
        </span>
      </div>

      <div class="w100 text-center text-bold text-caption q-pt-lg">
        {{ $t('subscribe_corp_dialog__tariffs_title') }}
      </div>
      <q-list class="q-pa-md">
        <q-list-item
          v-for="tariff in tariffs"
          :key="tariff.id"
          >
          <div class="flex justify-between no-wrap q-py-xs">
            <div class="column">
              <span class="text-bold">
                {{ tariff.name }}
              </span>
              <div class="flex no-wrap items-center text-caption" style="line-height: 1em;">
                <span v-if="tariff.chat_limit">
                  {{ $t('subscribe_tariffs__chats_max') + ' ' + tariff.chat_limit }}
                </span>
                <q-icon v-else name="mdi-all-inclusive" size="sm"/>
                <span class="q-pl-xs">
                  {{ $t('subscribe_tariffs__chats')}}
                </span>
              </div>
            </div>

            <div class="flex no-wrap items-center">
              <div class="text-h6">
                {{ tariff.price + ' ₽' }}
                <span class="text-caption q-pl-xs">
                  {{  $t('subscribe_tariffs__per_month') }}
                </span> 
              </div>
            </div>
          </div>
        </q-list-item>
      </q-list>

      <div style="white-space: pre-line" class="q-px-md text-caption">
        {{  $t('subscribe_corp_dialog__notes') }}
      </div>

      <div style="white-space: pre-line" class="q-px-md text-caption">
        {{  $t('subscribe_corp_dialog__doc') }}
      </div>

      <div style="white-space: pre-line" class="q-px-md text-caption">
        {{  $t('subscribe_corp_dialog__min_period') }}
      </div>
      
      <div style="white-space: pre-line" class="q-px-md text-caption">
        {{  $t('subscribe_corp_dialog__sale') }}
      </div>
    </pn-bottom-sheet-dialog>
  </pn-page-template>
</template>

<script setup lang="ts">
  import { ref, computed, inject, onMounted, onUnmounted } from 'vue'
  import { date, colors } from 'quasar'
  import { useCopyToClipboard } from 'composables/useCopyToClipboard'
  import subscribeUpgrade from 'components/subscribe/subscribeUpgrade.vue'
  import subscribeChangeRenew from 'components/subscribe/subscribeChangeRenew.vue'
  import { 
    getTariffs,
    getTariffDiscount
  } from 'composables/useSubscription'
  import { useAuthStore } from 'stores/auth'
  import type { Tariff } from 'types/Tariff'
  import type { WebApp } from '@twa-dev/types'

  const { copy } = useCopyToClipboard()
  const authStore = useAuthStore()

  const saleEmail = 'sale@tgcrew.ru'
  const customerTid = computed(() => authStore.customer?.external_id)

  const copyClick = async (text: string) => await copy(text)

  const tg = inject('tg') as WebApp
  // @ts-expect-error: get hex text
  tg.MainButton.color = colors.getPaletteColor('primary')

  const tariffs = ref<Tariff[] | null>(null)
  const discountTariff = ref(null)

  const testTariffId = computed(() => (tariffs.value && tariffs.value.find(el => el.price === 0))?.id ?? 1)
  const isCurrentTariffTest = computed(() => currentTariff.value?.id === testTariffId.value)

  const storeTariff = authStore.customer?.plan
  const currentTariff = computed(() => {
    if (tariffs.value && storeTariff) {
      const tariffInfo = tariffs.value.find((el: Tariff) => el.id === storeTariff.id)
      if (tariffInfo) return { ...storeTariff, tariffInfo }
    }
    return null
  })
  
  onMounted(async () => {
    tariffs.value = await getTariffs()
    discountTariff.value = await getTariffDiscount()
  })

  const basePeriods = [
    { id: 30, name: 'subscribe__1month', name_in_days: 'subscribe__30days' },
    { id: 91, name: 'subscribe__3months', name_in_days: 'subscribe__91days' },
    { id: 365, name: 'subscribe__1year', name_in_days: 'subscribe__365days' }
  ] as const

  const periods = computed(() => basePeriods.map(el => {
    const discount = discountTariff.value ? discountTariff.value[el.id] : 0
    return {
    ...el,
    discount
    }
  }))

  interface tgBtnData {
    status: 'hide' | 'show'
    url?: string
    textBtn?: string
  }

  const currentButtonHandler = ref<(() => void) | null>(null)
  
  function defaultTgBtn () {
    tg.MainButton.setText('-')
    tg.MainButton.hide()

    if (currentButtonHandler.value) {
      tg.MainButton.offClick(currentButtonHandler.value)
      currentButtonHandler.value = null
    }
  }
  
  function prepareTgBtn (btn: tgBtnData) {
    defaultTgBtn()

    if (btn.status === 'show' && btn.textBtn && btn.url) {

      tg.MainButton.setText(btn.textBtn)
      tg.MainButton.show()
      
      const handler = () => tg.openInvoice(btn.url!)
      currentButtonHandler.value = handler
      tg.MainButton.onClick(handler)
    }
  }

  onUnmounted(() => defaultTgBtn())

  const showDialogCorp = ref(false)
</script>

<style lang="scss">
</style>
