<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-wallets">
        <h1 class="loyalty-suite-wallets__title">{{ $t('walletsListMenu') }}</h1>
        <span v-if="!isPro" class="loyalty-suite-pro-limit">
          {{ $t('freeLimit1Item') }}
        </span>
        <q-btn v-if="isPro || totalPosts < 1" color="primary" icon="add" :label="$t('walletAdd')" :to="'/wallets/add'" />
      </div>
      <div class="loyalty-suite-wallets__table">
        <q-table flat bordered separator="cell" :rows="wallets" :columns="columns" row-key="id" :loading="loading"
          :rows-per-page-options="[10, 20, 50]" :rows-per-page-label="$t('recordsPerPage')"
          :no-data-label="$t('walletsTable.notFoundWallets')" v-model:pagination="pagination"
          :loading-label="$t('tableLoading')" @request="fetchWallets">
          <template v-slot:body-cell-name="props">
            <q-td :props="props">
              {{ props.row.name }}
              <a
                v-if="props.row.active"
                :href="`${viewUrl}/wallet/${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-transactions="props">
            <q-td :props="props">
              <router-link class="loyalty-suite-wallets__link" :to="'/wallets/transactions/' + props.row.id">
                <q-icon name="visibility" size="14px" />
                {{ $t('view') }}
              </router-link>
            </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="`/wallet/${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: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 wallets = ref<any[]>([]);

    const columns = [
      { name: 'name', label: t('walletsTable.name'), field: 'name', align: 'left', sortable: true, style: 'width: 40%', headerStyle: 'width: 55%;' },
      { name: 'unit', label: t('walletsTable.unit'), field: 'unit', align: 'left', sortable: false, style: 'width: 15%', headerStyle: 'width: 15%;' },
      { name: 'transactions', label: t('walletsTable.transactions'), field: 'transactions', align: 'left', sortable: false, style: 'width: 15%', headerStyle: 'width: 15%;' },
      { name: 'status', label: t('walletsTable.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 fetchWallets = 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_list, {
            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) {
          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');
        });

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

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

    return { loading, error, wallets, columns, pagination, formatStatus, fetchWallets, viewUrl, isPro, totalPosts };
  }
});
</script>

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

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

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

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

  &__link {
    display: inline-flex;
    width: auto;
    align-items: center;
    justify-content: center;
    text-decoration: none;
    font-size: 12px;
    line-height: 1;
    transition: 0.3s;
    border-radius: 1em;
    padding: 5px 10px;
    background: $accent;
    color: $primary;

    .q-icon {
      margin-right: 7px;
      color: $primary;
    }

    &:hover {
      background: $primary;
      color: $white;

      .q-icon {
        color: $white;
      }
    }
  }
}
</style>
