<template>
  <q-scroll-area class="loyalty-suite-wrapper">
    <div v-if="error" class="loyalty-suite-api-error-message">
      <q-icon name="error_outline" color="negative" size="md" />
      <span>{{ error }}</span>
    </div>
    <template v-else>
      <div class="loyalty-suite-challenges">
        <h1 class="loyalty-suite-challenges__title">{{ $t('challengesListMenu') }}</h1>
        <span v-if="!isPro" class="loyalty-suite-pro-limit">
          {{ $t('freeLimit3Items') }}
        </span>
        <div class="loyalty-suite-list__input-wrapper">
          <input
            v-model="searchQuery"
            :placeholder="$t('searchByName')"
            class="loyalty-suite-list__input"
            @update:model-value="onSearchChange"
          />
          <span v-if="searchQuery.length > 0" @click="clearQuery" class="loyalty-suite-list__input-clear">&times</span>
        </div>
        <q-btn v-if="isPro || totalPosts < 3" color="primary" icon="add" :label="$t('challengeAdd')" :to="'/challenges/add'" />
      </div>
      <div class="loyalty-suite-challenges__table">
        <q-table flat bordered separator="cell" :rows="challenges" :columns="columns" row-key="id" :loading="loading"
          :rows-per-page-options="[10, 20, 50]" :rows-per-page-label="$t('recordsPerPage')"
          :no-data-label="$t('challengesTable.notFoundChallenges')" v-model:pagination="pagination"
          :loading-label="$t('tableLoading')" @request="fetchChallenges">
          <template v-slot:body-cell-name="props">
            <q-td :props="props">
              {{ props.row.name }}
              <a
                v-if="props.row.active"
                :href="`${viewUrl}/challenge/${props.row.id}`"
                class="loyalty-suite-table-view-link"
                target="_blank"
              >
                <q-icon name="visibility" size="14px" />
                {{ $t('view') }}
              </a>
            </q-td>
          </template>
          <template v-slot:body-cell-actions="props">
            <q-td :props="props">
              <q-btn
                class="loyalty-suite-table-button-edit"
                flat
                dense
                round
                icon="edit"
                tag="router-link"
                :to="`/challenge/${props.row.id}`"
                @click.stop
              />
            </q-td>
          </template>
          <template v-slot:body-cell-status="props">
            <q-td :props="props">
              <q-badge :color="props.row.active ? 'green' : 'red'" rounded>
                {{ formatStatus(props.row.active) }}
              </q-badge>
            </q-td>
          </template>
          <template v-slot:body-cell-start_date="props">
            <q-td :props="props">
              {{ props.row.start_date ? props.row.start_date : '-' }}
            </q-td>
          </template>
          <template v-slot:body-cell-end_date="props">
            <q-td :props="props">
              {{ props.row.end_date ? props.row.end_date : '-' }}
            </q-td>
          </template>
          <template v-slot:loading>
            <q-inner-loading showing color="primary" />
          </template>
        </q-table>
      </div>
    </template>
  </q-scroll-area>
</template>

<script lang="ts">
import { ref, defineComponent, onBeforeMount } from 'vue';
import { useI18n } from 'vue-i18n';

export default defineComponent({
  setup() {
    const apiRoutes = window.loyalty_suite_admin_data.apiRoutes;
    const viewUrl = window.loyalty_suite_admin_data.homeUrl + window.loyalty_suite_admin_data.basePath;
    const nonce = window.loyalty_suite_admin_data.nonce;
    const loading = ref(true);
    const error = ref<string | null>(null);
    const isPro = window.loyalty_suite_admin_data.isPro;
    const totalPosts = ref(0);
    const { t } = useI18n();
    const challenges = ref<any[]>([]);
    const searchQuery = ref('');

    const columns = [
      { name: 'name', label: t('challengesTable.name'), field: 'name', align: 'left', sortable: true, style: 'width: 55%', headerStyle: 'width: 55%' },
      { name: 'start_date', label: t('challengesTable.startDate'), field: 'start_date', align: 'left', sortable: true, style: 'width: 15%', headerStyle: 'width: 15%' },
      { name: 'end_date', label: t('challengesTable.endDate'), field: 'end_date', align: 'left', sortable: true, style: 'width: 15%', headerStyle: 'width: 15%' },
      { name: 'status', label: t('challengesTable.status'), field: 'active', align: 'left', sortable: true, style: 'width: 15%', headerStyle: 'width: 15%' },
      { name: 'actions', label: t('edit'), field: 'actions', align: 'center', style: 'width: 50px; min-width: 50px', headerStyle: 'width: 50px; min-width: 50px' }
    ];

    const formatStatus = (active: boolean) => {
      return active ? t('enabled') : t('disabled');
    };

    const pagination = ref({
      page: 1,
      rowsPerPage: 10,
      rowsNumber: 0,
      sortBy: 'created_at',
      descending: false,
    });

    const fetchChallenges = async (props?: any) => {
      try {
        loading.value = true;
        error.value = null;

        const page = props?.pagination?.page || 1;
        const rowsPerPage = props?.pagination?.rowsPerPage || 10;
        const sortBy = props?.pagination?.sortBy || 'created_at';
        const descending = props?.pagination?.descending ? 'desc' : 'asc';
        const search = encodeURIComponent(searchQuery.value || '');

        const buildApiUrl = (base, params = {}) => {
          const url = new URL(base, window.location.origin);
          Object.entries(params).forEach(([key, value]) => {
            if (value !== undefined && value !== null && value !== '') {
              url.searchParams.set(key, value);
            }
          });
          return url.toString();
        };

        const response = await fetch(
          buildApiUrl(apiRoutes.admin.challenges_list, {
            page,
            per_page: rowsPerPage,
            order_by: sortBy,
            order: descending,
            search,
          }),
          {
            method: 'GET',
            headers: {
              'X-WP-Nonce': nonce,
              'Content-Type': 'application/json',
            },
            credentials: 'same-origin',
          }
        );

        if (!response.ok) {
          const errorText = await response.text();
          throw new Error(`API Error ${response.status}: ${errorText}`);
        }

        const data = await response.json().catch(() => {
          throw new Error('Invalid JSON response from API');
        });

        challenges.value = Array.isArray(data.challenges) ? data.challenges : [];
        totalPosts.value = data.total;
        pagination.value = {
          page,
          rowsPerPage,
          rowsNumber: data.total || 0,
          sortBy,
          descending: descending === 'desc',
        };
      } catch (err: any) {
        error.value = `Failed to load challenges: ${err.message}`;
        console.error('API Error:', err);
      } finally {
        loading.value = false;
      }
    };

    const onSearchChange = () => {
      const query = searchQuery.value || '';

      if (query.length >= 2 || query.length === 0) {
        fetchChallenges({ pagination: { ...pagination.value, page: 1 } });
      }
    };

    const clearQuery = () => {
      searchQuery.value = '';
      fetchChallenges({ pagination: { ...pagination.value, page: 1 } });
    };

    onBeforeMount(() => fetchChallenges({ pagination: pagination.value }));

    return {
      loading,
      error,
      challenges,
      columns,
      pagination,
      formatStatus,
      fetchChallenges,
      viewUrl,
      searchQuery,
      onSearchChange,
      clearQuery,
      isPro,
      totalPosts
    };
  }
});
</script>

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

  &__title {
    display: flex;
    font-size: 22px;
    margin-right: 20px;
  }

  .q-btn {
    margin-left: 20px;
    text-transform: uppercase;
    :deep(.q-btn__content) {
      flex-wrap: nowrap;
      white-space: nowrap;
    }
  }

  &__table {
    display: flex;
    width: 100%;
    flex-direction: column;
    margin-top: 25px;
  }

  &-modal {
    &__wrapper {
      max-width: 900px;
      width: 900px;
      padding: 20px 30px 30px 30px;

      &::-webkit-scrollbar {
        width: 10px;
      }

      &::-webkit-scrollbar-thumb {
        background: rgba(0, 0, 0, 0.2);
        border-radius: 3px;
        transition: 0.3s;
      }

      &::-webkit-scrollbar-thumb:hover {
        background: rgba(0, 0, 0, 0.3);
      }

      &::-webkit-scrollbar-track {
        opacity: 0;
      }
    }

    &__header {
      display: flex;
      align-items: center;
      width: 100%;
      padding: 0 5px;
      margin-bottom: 15px;
    }

    &__close {
      width: 24px;
      height: 24px;
      min-height: 24px;
      margin-left: auto;
      font-size: 8px;

      :deep(.q-btn__content) {
        padding-top: 1px;
      }

      :deep(.q-icon) {
        font-size: 14px !important;
      }
    }

    &__title {
      display: flex;
      font-size: 18px;
      font-weight: 700;
    }

    &__list {
      display: flex;
      width: 100%;
      flex-wrap: wrap;

      &-title {
        display: flex;
        align-items: center;
        width: 100%;
        font-weight: 700;
        font-size: 16px;
        margin: 15px 0 5px 0;
        padding: 0 5px;

        .loyalty-suite-form__row-hint {
          margin-top: 1px;
        }
      }
    }

    &__item {
      display: flex;
      width: 33.333333%;
      padding: 5px;

      &-wrapper {
        display: flex;
        width: 100%;
        border: 1px solid $border;
        border-radius: 4px;
        padding: 10px;
        transition: 0.3s;

        &:hover {
          cursor: pointer;
          border-color: $primary;
        }
      }

      &-icon {
        display: flex;
        width: 42px;
        flex-shrink: 0;
        align-items: center;
        justify-content: flex-start;
      }

      &-title {
        display: flex;
        width: 100%;
        font-weight: 700;
        margin-bottom: 5px;
      }

      &-content {
        display: flex;
        width: 100%;
        flex-direction: column;
      }

      &-description {
        display: flex;
        width: 100%;
      }
    }
  }
}
</style>
