<template>
  <div class="column w100 q-px-md">
    <div class="flex justify-end w100">
      <q-btn
        flat no-caps color="grey" rounded dense
        @click="showTarfiffSelectDialog = true"
        >
        <span class="q-px-xs text-caption">
          {{$t('subscribe__dialog_select_tariff_show')}}
        </span>
      </q-btn>
    </div>

    <div class="w100 text-grey text-center q-pt-sm">
      {{ t('subscribe__tariffs_interval_renewal') }}
    </div>
    
      <pn-subscribe-periods
        @update:selected="selectedPeriod = $event"
        :periods
        :tariff-price="selectedTariffPrice"
      />

    <div 
      class="text-caption column rounded-card q-px-md q-py-sm q-mt-md"
      style="border: 1px solid var(--q-negative);"
      v-if="currentTariff?.debt !== 0"
      >
      <div class="row justify-between item-center text-negative">
        <span>
          {{ $t('suscribe__credit_from') + ' ' +
            (currentTariff?.end_date
              ? date.formatDate(currentTariff?.end_date * 1000, 'DD.MM.YYYY')
              : '')
            + ': ' }}
        </span>
        <div class="flex no-wrap items-center q-pa-none q-ma-none">
          <telegram-star color="gold" size="12px" class="q-mr-xs"/>
          {{ formatNumber(currentTariff?.debt ?? '') }}
        </div>
      </div>
      <span class="text-grey">
        {{  $t('suscribe__credit_description') }}
      </span>
    </div>

    <div class="text-center text-grey w100 text-caption q-pt-lg">
      {{ $t('subscribe__promocode_description') }}
    </div>
    <q-input
      v-model="promocode"
      dense
      filled
      :label="$t('subscribe__promocode')"
      class="q-pt-sm"
      >
      <template #append v-if="promocode !== ''">
        <q-btn
          round dense flat
          color="primary"
          icon="mdi-arrow-right-circle-outline"
          @click="clickSendPromocode"
        />
      </template>
    </q-input>
  </div>
  <pn-bottom-sheet-dialog
    v-if="tariffs && currentTariff"
    title="subscribe__dialog_select_tariff_title"
    v-model="showTarfiffSelectDialog"
    >

    <div class="w100 column">
      <q-banner
        v-if="!currentTariff.can_change"
        class="bg-negative text-white q-mb-md"
        >
        <div>
          {{ $t(messageBlockChange?.body ?? '') }}
        </div>
        <div class="text-caption" style="opacity: 0.8">
          {{ $t(messageBlockChange?.description ?? '') }}
        </div>
      </q-banner>
      <pn-subscribe-tariffs
        @update:selected="selectedTariff = $event"
        :tariffs
        :currentTariffId="currentTariff.id"
        :disable="!currentTariff.can_change"
      />
      <div class="text-caption text-grey q-px-md q-py-md">
        <div class="w100">
          {{ $t('subscribe__dialog_select_tariff_notes_title') }}
        </div>
        <div class="w100">
          {{ $t('subscribe__dialog_select_tariff_notes_1') }}
        </div>
        <div class="w100">
          {{ $t('subscribe__dialog_select_tariff_notes_2') }}
        </div>
        <div class="w100">
          {{ $t('subscribe__dialog_select_tariff_notes_3') }}
        </div>

        <div
          class="w100 text-info cursor-pointer"
          @click="router.push({ name: 'tariffs_info'})"  
          >
          {{ $t('subscribe__dialog_select_tariff_notes_more') }}
        </div>
      </div>
    </div>

    <template #footer>
      <div class="column">
        <q-btn
          rounded
          class="w100"
          color="primary"
          v-close-popup
          :outline="!currentTariff.can_change || currentTariff?.id === selectedTariff"
          @click="clickChangeTariff"
          >
          {{ $t(currentTariff.can_change && currentTariff?.id !== selectedTariff
            ? 'subscribe__dialog_select_tariff_btn'
            : 'subscribe__dialog_select_tariff_btn_cancel' 
          ) }}
        </q-btn>
        <div
          v-if="props.currentTariff?.id !== selectedTariff"
          class="q-px-md text-caption text-negative text-center"
          >
          {{ $t('subscribe__dialog_select_tariff_recalc_msg') + ': ' }} 
          {{
            typeof activePeriodMessage === 'number'
              ? date.formatDate(activePeriodMessage * 1000, 'DD.MM.YYYY')
              : 'Error'
          }}
        </div>
        <div style="height: 30px"/>
      </div>
    </template>
  </pn-bottom-sheet-dialog>
</template>

<script setup lang="ts">
  import { ref, computed, watch } from 'vue'
  import { useRouter } from 'vue-router'
  import { useI18n } from 'vue-i18n'
  import { date, useQuasar } from 'quasar'
  import { formatNumber } from 'utils/helpers'
  import telegramStar from 'components/TelegramStar.vue'
  import pnSubscribeTariffs from 'components/subscribe/pnSubscribeTariffs.vue'
  import pnSubscribePeriods from 'components/subscribe/pnSubscribePeriods.vue'
  import { 
    calcChangeTariff,
    changeTariff,
    calcRenewTariff,
    urlRenewTariff,
    sendPromocode
  } from 'composables/useSubscription'
  import type { Tariff, CurrentTariff, TariffPeriod } from 'types/Tariff'

  const { t } = useI18n()
  const router = useRouter()

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

  const emit = defineEmits(['update'])

  const selectedTariff = ref<number>()
  const selectedPeriod = ref<number>()

  const selectedTariffPrice = computed(() => props.tariffs.find((el: Tariff) => el.id === props.currentTariff?.id)?.price ?? 0)

  const showTarfiffSelectDialog = ref(false)

  async function clickChangeTariff () {
    if (props.currentTariff &&
      selectedTariff.value &&
      props.currentTariff.can_change &&
      props.currentTariff?.id !== selectedTariff.value)
      await changeTariff(selectedTariff.value)
  }
  
  const messageBlockChange = computed(() => {
    if (props.currentTariff && !props.currentTariff.can_change) {
      return props.currentTariff.debt === 0
        ? { 
            body: 'subscribe__dialog_select_tariff_warn_debt_msg_1', 
            description: 'subscribe__dialog_select_tariff_warn_debt_msg_2'
          } 
        : {
            body: 'subscribe__dialog_select_tariff_warn_once_day_msg_1', 
            description: 'subscribe__dialog_select_tariff_warn_once_day_msg_2'
          }
    }
    return {}
  })

  const activePeriodMessage = ref('')
  watch(selectedTariff, async (newVal) => {
    activePeriodMessage.value = (newVal && newVal !== props.currentTariff?.id )
      ? (await calcChangeTariff(newVal)).plan_end_date
      : ''
  })

  watch(showTarfiffSelectDialog, async (newVal) => {
    if (newVal) emit('update', { status: 'hide' })
    else await updatePayment()
  })

  watch(selectedPeriod, async () => await updatePayment())

  const updatePayment = async () => {
    if (!props.currentTariff?.id || !selectedPeriod.value) return
  
    const renew = await calcRenewTariff(props.currentTariff.id, selectedPeriod.value)
    const textBtn = t('subscribe__pay_renew') + ' ⭐' + formatNumber(renew.amount) +
      ' (' + t('subscribe__tariff_exp') + ' ' + date.formatDate(renew.end_date * 1000, 'DD.MM.YYYY') + ')'
    const url = urlRenewTariff(props.currentTariff.id, selectedPeriod.value)

    emit('update', { status: 'show', textBtn, url })
  }

  // promocode
  const promocode = ref('')
  const $q = useQuasar()

  async function clickSendPromocode () {
    const result = await sendPromocode(promocode.value)
    
    if (result) showNotify('success')
    else showNotify('fail')
    
    promocode.value = ''
  }

  const showNotify = (message: 'success' | 'fail') => {
    $q.notify({
      message: t(message === 'success' ? 'subscribe__promocode_success' : 'subscribe__promocode_fail'),
      type: message === 'success' ? 'positive' : 'negative',
      timeout: 1000,
      multiLine: true
    })
  }

</script>

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