<template>
  <div class="loyalty-suite-wrapper">
    <div class="loyalty-suite-loading" v-if="loading">
      <div class="loyalty-suite-spinner"></div>
    </div>

    <template v-else>
      <div v-if="errorMessage" class="loyalty-suite-api-error-message">
        <span>{{ errorMessage }}</span>
      </div>
      <template v-if="!error">
        <div class="loyalty-suite-my-rewards">
          <div class="loyalty-suite-my-rewards__breadcrumbs">
            {{ $t('myRewards') }}
          </div>
          <div class="loyalty-suite-my-rewards__header">
            <Select v-model="sorting" :options="sortingOptions" :label="$t('sortBy')" />
          </div>
          <div class="loyalty-suite-my-rewards__list">
            <Reward v-for="(reward, index) in rewards" :key="reward.id || index" :reward="reward" />
            <div v-if="!rewards.length" class="loyalty-suite-my-rewards__empty">
              {{ $t('noMyRewards') }}
            </div>
          </div>
          <span v-if="!isLastPage" @click="loadMore"
            :class="['loyalty-suite-button', { 'loyalty-suite-button_loading': isLoadingMore }]">
            {{ $t('loadMore') }}
          </span>
        </div>
      </template>
    </template>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, onBeforeMount, computed, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import Reward from '../components/Reward.vue';
import Select from '@/components/Select.vue';

export default defineComponent({
  components: { Reward, Select },
  setup() {
    const loading = ref(true);
    const error = ref<string | null>(null);
    const apiRoutes = window.loyalty_suite_account_data.apiRoutes;
    const nonce = window.loyalty_suite_account_data.nonce;
    const { t } = useI18n();
    const rewards = ref([]);
    const sorting = ref('all');
    const page = ref(1);
    const achievements = ref([]);
    const isLastPage = ref(true);
    const isLoadingMore = ref(false);
    const sortingOptions = ref([
      { value: 'active', label: t('activeReward') },
      { value: 'used', label: t('usedReward') },
      { value: 'expired', label: t('expiredReward') },
      { value: 'all', label: t('allReward') },
    ]);

    const errorMessage = computed(() => {
      if (error.value === '401') {
        return;
      }
      return null;
    });

    watch(sorting, (newVal) => {
      loading.value = true;
      page.value = 1;
      fetchData(newVal);
    });

    const loadMore = () => {
      page.value += 1;
      isLoadingMore.value = true;
      fetchData(sorting.value, page.value, true);
    };

    const fetchData = async (orderBy = 'all', page = 1, append = false) => {
      try {
        const url = new URL(apiRoutes.account.rewards);
        url.searchParams.set('per_page', '12');
        url.searchParams.set('order_by', orderBy);
        url.searchParams.set('page', String(page));

        const response = await fetch(url.toString(), {
          method: 'GET',
          headers: {
            'X-WP-Nonce': nonce,
            'Content-Type': 'application/json',
          },
        });

        if (!response.ok) throw new Error(response.status);

        const data = await response.json();
        isLastPage.value = data.is_last_page;

        if (append) {
          rewards.value.push(...data.posts);
        } else {
          rewards.value = data.posts;
        }
      } catch (err: any) {
        error.value = err.message === '401' ? '401' : err.message || t('couldNotFetchData');
        console.error('API Error:', error.value);
      } finally {
        loading.value = false;
        isLoadingMore.value = false;
      }
    };

    onBeforeMount(fetchData);

    return { loading, error, errorMessage, sorting, sortingOptions, rewards, loadMore, isLastPage, isLoadingMore };
  },
});
</script>

<style lang="scss" scoped>
.loyalty-suite-my-rewards {
  display: flex;
  width: 100%;
  flex-direction: column;

  &__breadcrumbs {
    display: flex;
    width: 100%;
    font-weight: 700;
    margin-top: 5px;
    margin-bottom: 20px;
    color: var(--loyalty-suite-primary);
  }

  &__header {
    display: flex;
    width: 100%;
    white-space: nowrap;
    align-items: center;
    margin-bottom: 10px;
  }

  &__list {
    width: calc(100% + 20px);
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
    margin: 0 -10px;
  }

  &__empty {
    display: flex;
    padding: 0 10px;
  }

  .loyalty-suite-button {
    align-self: center;
    margin-top: 15px;
  }
}
</style>
