<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-challenges">
          <div v-if="challenges.length && IsUserLoggedIn" class="loyalty-suite-challenges__header">
            <Select v-model="sorting" :options="sortingOptions" :label="$t('sortBy')" />
          </div>
          <div class="loyalty-suite-challenges__list">
            <Challenge v-for="(challenge, index) in challenges" :key="challenge.id || index" :challenge="challenge"
              :style="cardStyle" />
            <div v-if="!challenges.length" class="loyalty-suite-challenges__empty">
              {{ $t('noChallenges') }}
            </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 Challenge from '../components/Challenge.vue';
import Select from '@/components/Select.vue';

export default defineComponent({
  components: { Challenge, 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 IsUserLoggedIn = window.loyalty_suite_account_data.isUserLoggedIn;
    const { t } = useI18n();
    const sorting = ref('created_at');
    const page = ref(1);
    const isLastPage = ref(true);
    const cardStyle = ref('classic');
    const isLoadingMore = ref(false);
    const challenges = ref([]);
    const sortingOptions = ref([
      { value: 'created_at', label: t('dateSort') },
      { value: 'main_progress', label: t('inProgressSort') },
    ]);

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

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

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

    const fetchData = async (orderBy = 'created_at', page = 1, append = false) => {
      try {
        const url = new URL(apiRoutes.account.challenges);
        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;
        cardStyle.value = data.card_style;

        if (append) {
          challenges.value.push(...data.posts);
        } else {
          challenges.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,
      challenges,
      loadMore,
      isLastPage,
      isLoadingMore,
      cardStyle,
      IsUserLoggedIn
    };
  },
});
</script>

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

  &__header {
    display: flex;
    width: 100%;
    white-space: nowrap;
    align-items: center;
    margin-top: 5px;
    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: 10px;
  }

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