<template>
  <!-- only for test tariff -->
  <div 
    class="column w100" 
    v-if="testTariffId && tariffs.length > 0 && periods.length > 0"
    >
    <div class="w100 text-bold text-center">
        {{ $t('subscribe__tariffs') }}
    </div>
    <pn-subscribe-tariffs
      @update:selected="selectedTariff = $event"
      :tariffs
    />
    <q-slide-transition>
      <div v-if="selectedTariff !== testTariffId">
      <div class="w100 text-bold text-center q-pt-md">
        {{ $t('subscribe__tariffs_interval') }}
      </div>
      <pn-subscribe-periods
        @update:selected="selectedPeriod = $event"
        :periods
        :tariff-price="selectedTariffPrice"
        class="q-px-md"
      />
      </div>
    </q-slide-transition>
  </div>
</template>

<script setup lang="ts">
  import { ref, computed, watch } from 'vue'
  import { useI18n } from 'vue-i18n'
  import { date } from 'quasar'
  import { formatNumber } from 'utils/helpers'
  import pnSubscribeTariffs from 'components/subscribe/pnSubscribeTariffs.vue'
  import pnSubscribePeriods from 'components/subscribe/pnSubscribePeriods.vue'
  import { 
    calcUpgradeTariff,
    urlUpgradeTariff
  } from 'composables/useSubscription'
  import type { Tariff, TariffPeriod } from 'types/Tariff'

  const { t } = useI18n()

  const props = defineProps<{
    tariffs: Tariff[]
    periods: TariffPeriod[]
  }>()

  const emit = defineEmits(['tariff-upgrade'])
  
  const selectedTariff = ref<number>()
  const selectedPeriod = ref<number>()

  const testTariffId = computed(() => props.tariffs.find(el => el.price === 0)?.id ?? null)
  const selectedTariffPrice = computed(() => props.tariffs.find((el: Tariff) => el.id === selectedTariff.value)?.price ?? 0)

  watch([selectedTariff, selectedPeriod], async () => {
    if (selectedTariff.value === testTariffId.value) {
      emit('tariff-upgrade', { status: 'hide' })
      return
    }
    
    if (!selectedTariff.value || !selectedPeriod.value) return
    
    const upgrade = await calcUpgradeTariff(selectedTariff.value, selectedPeriod.value)
    const textBtn = t('subscribe__pay') + ' ⭐' + formatNumber(upgrade.amount) +
      ' (' + t('subscribe__tariff_exp') + ' ' + date.formatDate(upgrade.end_date * 1000, 'DD.MM.YYYY') + ')'
    const url = await urlUpgradeTariff(selectedTariff.value, selectedPeriod.value)

    emit('tariff-upgrade', { status: 'show', textBtn, url })
  })
</script>

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