<!-- eslint-disable @typescript-eslint/ban-ts-comment -->
<!-- eslint-disable @typescript-eslint/ban-ts-comment -->
<!-- eslint-disable @typescript-eslint/ban-ts-comment -->
<template>
  <pn-page-card>
    <template #title>
      {{$t('subscribe__title')}}
    </template>

    <pn-scroll-list >
      <div class="q-px-md">
        <div
          id="subscribe-current-balance"
          class="flex w100 q-px-md q-py-sm row"
          style="border-radius: var(--top-raduis); border: 1px solid var(--q-primary);"
          >

          <div class="flex w100 justify-between items-center no-wrap">
            <div class="flex no-wrap items-center text-h6 col-9">
              {{ $t('subscribe__current_plan') }}
            </div>

            <div class="flex items-center column col-3">
              <span class="text-bold">
                {{ currentPlanData?.name }}
              </span>
              <span class="text-caption" style="line-height: 0.5em;">
                {{ $t('subscribe__plan_exp') }}
                {{ date.formatDate(currentPlanData.exp * 1000, 'DD.MM.YYYY') }}
              </span>
            </div>
          </div>

          <div class="flex row w100 ow-wrap items-center text-caption q-pt-sm">
            <div class="col-9">{{ $t('subscribe__plan_active_chats') }}</div>
            <div class="col-3" align="center">
              <span class="text-brand2 text-bold q-pr-xs">{{ currentPlanData?.active_chats }}</span>
              <span class="text-grey">/{{ currentPlanData?.chatsQty }}</span>
            </div>
          </div>

        </div>
          <div class="flex w100 justify-center text-grey q-pt-md q-pb-none">{{ $t('subscribe__plans')}}</div>
          <q-list separator>
            <q-item
              v-for="item in plans"
              :key="item.id"
              >
              <q-item-section avatar>
                <q-radio v-model="newPlan" :val="item" v-if="item.name!=='TEST'"/>
              </q-item-section>
              <q-item-section>
                <q-item-label class="text-bold">{{ item.name }}</q-item-label>
                <div class="flex no-wrap items-center text-caption">
                  <span v-if="item.chatsQty" class="q-pr-xs">
                    {{ $t('subscribe__chats_max') }}
                  </span>
                  <span v-if="item.chatsQty">
                    {{ item.chatsQty }}
                  </span>
                  <q-icon v-else name="mdi-all-inclusive" size="sm"/>
                  <span class="q-pl-xs">
                    {{ $t('subscribe__chats')}}
                  </span>
                </div>
              </q-item-section>
              <q-item-section side>
                <div v-if="item.price" class="flex column items-center">
                  <div class="flex no-wrap items-center">
                    <telegram-star color="gold" size="18px" class="q-mr-xs"/>
                    <span class="text-h6">{{ formatNumber(item.price) }}</span>
                    <span class="text-caption q-pl-xs">{{ $t('subscribe__per_month') }}</span>
                  </div>
                </div>
                <div v-else class="text-bold">
                  {{ $t('subscribe__free_tax') }}
                </div>
              </q-item-section>
            </q-item>
          </q-list>
          <div class="flex w100 justify-center text-caption text-grey q-pt-sm text-center">
            {{ $t('subscribe__plans_description') }}
          </div>
          
          <q-btn-group spread flat class="w100 q-py-sm">  
            <q-btn
              v-for="period in periods"
              :key="period.id"
              :color="selectPeriod === period.value ? 'primary' : 'white'"
              :text-color="selectPeriod === period.value ? 'white' : 'primary'"
              @click="selectPeriod = period.value"
              no-caps
              >
              <div class="column items-center w100 self-end">
                <q-badge v-show="period.sale" color="red">{{ period.sale }}% off</q-badge>
                <span>{{ $t(period.name) }}</span>
                <span class="text-caption">({{ $t(period.name_in_days) }})</span>
              </div>
            </q-btn>
          </q-btn-group>

          <div class="text-caption column text-grey">
            <span>{{ $t('subscribe__plans_period_notes') + ' ' }}</span>
            <span
              @click="router.push({ name: 'change_plan_rules' })"
              class="text-info cursor-pointer"  
              >
              {{ $t('subscribe__plans_period_notes_more_info') }}
            </span>
          </div>

      </div>
    </pn-scroll-list>
  </pn-page-card>
</template>

<script setup lang="ts">
  import { ref, computed, inject, onUnmounted, watch } from 'vue'
  import telegramStar from 'components/TelegramStar.vue'
  import { useRouter } from 'vue-router'
  import { date } from 'quasar'
  import { useI18n } from 'vue-i18n'
  import type { WebApp } from '@twa-dev/types'
  import { colors } from 'quasar';

  const router = useRouter()

  const tg = inject('tg') as WebApp
  tg.MainButton.show()

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

  const plans = [
    { id: 1, name: 'TEST', val: 'test', price: null, chatsQty: 5 },
    { id: 2, name: 'START', val: 'start', price: 1000, chatsQty: 15 },
    { id: 3, name: 'PRO', val: 'pro', price: 5000, chatsQty: 40 },
    { id: 4, name: 'VIP', val: 'vip', price: 12000, chatsQty: null }
  ] as const

  const periods = [
    { id: 1, name: 'subscribe__1month', name_in_days: 'subscribe__30days', value: 30, sale: 0 },
    { id: 2, name: 'subscribe__3months', name_in_days: 'subscribe__91days', value: 91, sale: 5 },
    { id: 3, name: 'subscribe__1year', name_in_days: 'subscribe__365days', value: 365, sale: 15 }
  ]

  const selectPeriod = ref(periods[1]?.value)

  const newPlan = ref(plans[1])

  interface CurrentPlan {
    plan: string
    exp: number | null
    active_chats: number | null
  }
  
  const currentPlan =  ref<CurrentPlan>({ // temp, this get from api
    plan: plans[0].val,
    active_chats: 20,
    exp: Date.now() / 1000 + 500000
  })

  interface CurrentPlanData extends CurrentPlan {
    price: number | null
  }
  
  const currentPlanData = computed((): CurrentPlanData => ({
    active_chats: currentPlan.value.active_chats ?? null,
    exp: currentPlan.value.exp ?? null,
    ...plans.find(el=> el?.val === currentPlan.value.plan)
  }))

  const { t } = useI18n()
  const textBtn = computed(() => {
    const prorata = currentPlanData.value.price
      ? Math.ceil(
        currentPlanData.value?.price / 30 * 
        date.getDateDiff(new Date(currentPlan.value.exp * 1000), Date.now())
      )
      : 0
    const k = 1 - Number(periods.find(el => el.value === selectPeriod.value)?.sale) / 100
    const stars = formatNumber(
      Number(selectPeriod.value) *
      Number(newPlan.value?.price) *
      k - prorata
    )
    const newDateExp = date.addToDate(Date.now(), { months: Number(selectPeriod.value) })

    return t('subscribe__pay') + ' ⭐' + stars + 
      ' (' + t('subscribe__plan_exp') + ' ' +
      date.formatDate(newDateExp, 'DD.MM.YYYY') + ')'
  })


  function formatNumber (number: string | number) {
    return number.toString().replace(/\B(?=(\d{3})+(?!\d))/g, " ")
  }

  onUnmounted(() => tg.MainButton.hide())

  watch(textBtn, () => tg.MainButton.setText(textBtn.value),
  { immediate: true })

</script>

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