<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-transactions">
        <h1 class="loyalty-suite-transactions__title">{{ $t('transactionsListMenu') }}</h1>
        <router-link :to="`/wallet/${wallet.id}`" class="loyalty-suite-transactions__link">{{ wallet.name }}</router-link>
        <q-btn
          color="primary"
          icon="add"
          :label="$t('transactionAdd')"
          :to="{ path: '/wallets/transactions/add', query: { wallet: wallet.id } }"
        />
      </div>
      <div class="loyalty-suite-transactions__table">
        <q-table flat bordered separator="cell" :rows="transactions" :columns="columns" row-key="id" :loading="loading"
          :rows-per-page-options="[10, 20, 50]" :rows-per-page-label="$t('recordsPerPage')"
          :no-data-label="$t('transactionsTable.notFoundTransactions')" v-model:pagination="pagination"
          :loading-label="$t('tableLoading')" @request="fetchTransactions">
          <template v-slot:body-cell-value="props">
            <q-td :props="props">
              {{ props.row.amount }}
            </q-td>
          </template>
          <template v-slot:body-cell-source_type="props">
            <q-td :props="props">
              {{ $t(props.row.source_type + 'Transaction') }}
            </q-td>
          </template>
          <template v-slot:body-cell-source="props">
            <q-td :props="props">
              <a v-if="props.row.source.url.length > 0" :href="props.row.source.url" class="loyalty-suite-transactions__table-link" target="_blank">
                {{ $t(props.row.source.label + 'Transaction') + ' ' + props.row.source.number }}
              </a>
              <template v-if="props.row.source_type === 'reward'">
                {{ props.row.source.label }}
              </template>
              <template v-if="props.row.source_type === 'refundReward'">
                {{ props.row.source.label }}
              </template>
              <template v-if="props.row.source_type === 'admin'">
                {{ $t('adminTransaction') }}
              </template>
            </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 { defineComponent, ref, computed, onBeforeMount } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRoute } from 'vue-router';

export default defineComponent({
  setup() {
    const loading = ref(true);
    const error = ref<string | null>(null);
    const apiRoutes = window.loyalty_suite_admin_data.apiRoutes;
    const nonce = window.loyalty_suite_admin_data.nonce;
    const { t } = useI18n();
    const route = useRoute();
    const transactions = ref([]);
    const wallet = ref([]);

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

    const columns = computed(() => [
      { name: 'date', label: t('date'), field: 'created_at', align: 'left', sortable: true, style: 'width: 15%', headerStyle: 'width: 15%;' },
      { name: 'user', label: t('user'), field: 'user', align: 'left', sortable: false, style: 'width: 20%', headerStyle: 'width: 20%;' },
      { name: 'source_type', label: t('transaction'), field: 'source_type', align: 'left', sortable: false, style: 'width: 20%', headerStyle: 'width: 20%;' },
      { name: 'source', label: t('sourceTransaction'), field: 'source', align: 'left', sortable: false, style: 'width: 20%', headerStyle: 'width: 20%;' },
      { name: 'amount', label: wallet.value?.unit_plural || t('amount'), field: 'amount', align: 'left', sortable: false, style: 'width: 15%', headerStyle: 'width: 15%;' },
    ]);

    const fetchTransactions = 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 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.wallets_transactions, {
            id: Number(route.params.id),
            page,
            per_page: rowsPerPage,
            order_by: sortBy,
            order: descending,
          }),
          {
            method: 'GET',
            headers: {
              'X-WP-Nonce': nonce,
              'Content-Type': 'application/json',
            },
            credentials: 'same-origin',
          }
        );

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

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

    const fetchWallet = async () => {
      try {
        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.wallet, { id: Number(route.params.id) }),
          {
            method: 'GET',
            headers: {
              'X-WP-Nonce': nonce,
              'Content-Type': 'application/json',
            },
            credentials: 'same-origin',
          }
        );

        const data = await response.json().catch(() => null);

        if (!response.ok) {
          error.value = data?.error;
          return;
        }

        wallet.value = {
          id: Number(route.params.id) ?? null,
          ...data.wallet,
        };
      } catch (err) {
        error.value = err instanceof Error ? err.message : t('couldNotFetchData');
        console.error('API Error:', error.value);
      }
    };

    onBeforeMount(async () => {
      await Promise.all([fetchTransactions({ pagination: pagination.value }), fetchWallet()]);
      loading.value = false;
    });

    return {
      loading,
      error,
      columns,
      pagination,
      transactions,
      fetchTransactions,
      wallet
    };
  },
});
</script>

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

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

  .q-btn {
    margin-left: auto;
    text-transform: uppercase;
  }

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

    a.loyalty-suite-transactions__table-link {
      display: flex;
      font-weight: 400;
      text-decoration: none;
      color: $primary;
    }
  }
  a.loyalty-suite-transactions__link {
    display: flex;
    font-weight: 400;
    font-size: 22px;
    line-height: normal;
    text-decoration: none;
    margin-left: 5px;
    color: $primary;
    &:hover {
      color: $primary;
    }
  }
}
</style>
