<template>
  <div class="w100">
    <q-btn-group spread flat class="w100 q-py-xs">
      <q-btn
        v-for="period in periods"
        :key="period.id"
        :outline="selectedPeriod === period.id"
        @click="selectedPeriod = period.id"
        :color="selectedPeriod === period.id  ? 'primary' : ''"
        no-caps dense
        >
        <div class="column items-center w100 self-start">
          <span
            class="text-caption text-grey text-no-wrap"
            >
            {{ $t(period.name_in_days) }}
          </span>

          <div
            class="text-h6"
            :class="selectedPeriod === period.id  ? 'text-primary' : 'text-black'"
            style="line-height: 1em !important;"
            >
            {{ $t(period.name) }}
          </div>
          <div
            class="row no-wrap w100 q-px-sm q-pt-xs justify-center"
            >
            <div
              v-if="getPeriodPrice(period)"
              class="flex no-wrap text-caption text-grey items-center q-pa-none q-ma-none q-pr-xs"
              >
              <telegram-star color="gold" size="12px" class="q-mr-xs"/>
              {{ formatNumber(getPeriodPrice(period)) }}
            </div>  
            
            <q-badge color="red" class="q-px-xs" v-if="period.discount">
              -{{ period.discount * 100 }}%
            </q-badge>
          </div>
        </div>
      </q-btn>
    </q-btn-group>
  </div>
</template>

<script setup lang="ts">
  import { ref, watch } from 'vue'
  import telegramStar from 'components/TelegramStar.vue'
  import { formatNumber } from 'utils/helpers'
  import type { TariffPeriod } from 'types/Tariff'

  const props = defineProps<{
    periods: TariffPeriod[],
    tariffPrice: number
  }>()

   

  const emit = defineEmits(['update:selected'])
  
  const selectedPeriod = ref<number>()

  watch(() => props.periods, () => {
    if (props.periods.length !== 0) {
      selectedPeriod.value = props.periods[0]?.id
    }
  }, { immediate: true })

  watch(selectedPeriod, (newVal) => {
    if (newVal !== undefined) emit('update:selected', newVal)
  }, { immediate: true })

  function getPeriodPrice (period: TariffPeriod) {
    return Math.floor(props.tariffPrice * (1 - period.discount) * period.id / 30)
  }

</script>

<style scoped>
</style>
