<script setup lang="ts">
import { ref, onMounted, onActivated } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRouter, RouterLink } from 'vue-router';
import api from '../../api';
import GoldSpinner from '../../components/GoldSpinner.vue';
import Pagination from '../../components/desktop/Pagination.vue';
import DesktopWalletSubNav from '../../components/desktop/DesktopWalletSubNav.vue';
import { formatMoney } from '../../utils/localeDisplay';
import { txTypeKey, txDisplayType, txAmountClass, txSummaryLabel } from '../../utils/walletTx';
import { parseCashbackApiData, sumCashbackAmount } from '../../utils/cashback';

const { t, locale } = useI18n();
const router = useRouter();

type Transaction = {
  transactionType: string;
  displayType?: string;
  summary?: string | null;
  summaryKind?: 'opening_bonus' | null;
  referenceType?: string | null;
  amount: string;
  frozenBefore?: string;
  frozenAfter?: string;
  createdAt: string;
  transactionId: string;
};

const items = ref<Transaction[]>([]);
const cashbackTotal = ref('0');
const loading = ref(true);
const page = ref(1);
const pageSize = ref(20);
const total = ref(0);

function txLabel(tx: Transaction): string {
  const key = txTypeKey(txDisplayType(tx));
  if (key) {
    const translated = t(key);
    if (translated !== key) return translated;
  }
  return tx.transactionType;
}

function txSubtitle(tx: Transaction): string {
  return txSummaryLabel(tx, t);
}

function amountClass(amount: string) {
  return `desktop-records-amount ${txAmountClass(amount)}`;
}

async function fetchData(p = 1) {
  loading.value = true;
  try {
    const [txRes, cbRes] = await Promise.all([
      api.get('/player/wallet/transactions', { params: { page: p, pageSize: pageSize.value } }),
      p === 1 ? api.get('/player/cashbacks').catch(() => ({ data: { data: [] } })) : Promise.resolve(null),
    ]);
    const result = txRes.data.data ?? { items: [], total: 0, pageSize: pageSize.value };
    total.value = result.total ?? 0;
    if (p === 1) {
      items.value = result.items ?? [];
      const cbRows = parseCashbackApiData(cbRes?.data?.data);
      cashbackTotal.value = sumCashbackAmount(cbRows).toString();
    } else {
      items.value = result.items ?? [];
    }
    page.value = p;
  } catch {
    /* ignore */
  } finally {
    loading.value = false;
  }
}

onMounted(() => fetchData(1));
onActivated(() => fetchData(1));
</script>

<template>
  <div class="desktop-records-page">
    <header class="desktop-records-header">
      <div class="desktop-records-header-main">
        <DesktopWalletSubNav />
      </div>
      <div class="desktop-records-actions">
        <RouterLink to="/wallet/recharge" class="desktop-records-action-btn">
          {{ t('wallet.recharge_btn') }}
        </RouterLink>
      </div>
    </header>

    <section v-if="loading && !items.length" class="desktop-records-panel">
      <div class="desktop-records-loading">
        <GoldSpinner :size="36" />
      </div>
    </section>

    <section v-else-if="items.length" class="desktop-records-panel">
      <div class="desktop-records-table-wrap">
        <table class="desktop-records-table">
          <thead>
            <tr>
              <th>{{ t('wallet.type') || '类型' }}</th>
              <th>{{ t('wallet.note') || '备注' }}</th>
              <th class="num-th">{{ t('wallet.amount') || '金额' }}</th>
              <th>{{ t('wallet.time') || '时间' }}</th>
            </tr>
          </thead>
          <tbody>
            <tr
              v-for="tx in items"
              :key="tx.transactionId"
              class="hover-row"
              style="cursor: pointer"
              @click="router.push(`/wallet/transactions/${tx.transactionId}`)"
            >
              <td class="type-cell">{{ txLabel(tx) }}</td>
              <td class="muted-cell">{{ txSubtitle(tx) || '-' }}</td>
              <td :class="['num-cell', amountClass(tx.amount)]">{{ formatMoney(tx.amount, locale) }}</td>
              <td class="date-cell">{{ new Date(tx.createdAt).toLocaleString() }}</td>
            </tr>
          </tbody>
        </table>
      </div>
      <div class="desktop-records-pagination">
        <Pagination
          v-if="total > 0"
          v-model="page"
          v-model:pageSize="pageSize"
          :total="total"
          @change="fetchData"
        />
      </div>
    </section>

    <section v-else class="desktop-records-panel">
      <div class="desktop-records-empty">
        <span>{{ t('wallet.no_records') }}</span>
      </div>
    </section>
  </div>
</template>

<style scoped>
.type-cell {
  font-weight: 700;
}

.muted-cell {
  color: var(--text-muted);
  max-width: 420px;
}
</style>
