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

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

const detailModalVisible = ref(false);
const detailTxId = ref<string | null>(null);

function openDetail(txId: string) {
  detailTxId.value = txId;
  detailModalVisible.value = true;
}

function openDetailFromQuery() {
  const transactionId = route.query.transactionId;
  if (typeof transactionId === 'string' && transactionId) {
    openDetail(transactionId);
    const { transactionId: _removed, ...rest } = route.query;
    void router.replace({ path: route.path, query: rest });
  }
}

watch(() => route.query.transactionId, openDetailFromQuery);

type Transaction = {
  transactionType: string;
  displayType?: string;
  summary?: string | null;
  amount: string;
  createdAt: string;
  transactionId: string;
};

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

function txLabel(tx: Transaction) {
  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 { data } = await api.get('/player/wallet/transactions', {
      params: { page: p, pageSize: pageSize.value },
    });
    const result = data.data ?? { items: [], total: 0, pageSize: pageSize.value };
    total.value = result.total ?? 0;
    items.value = result.items ?? [];
    page.value = p;
  } catch {
    if (p === 1) items.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
}

onMounted(() => {
  void fetchData(1);
  openDetailFromQuery();
});
onActivated(() => {
  void fetchData(page.value);
  openDetailFromQuery();
});
</script>

<template>
  <div class="desktop-records-page">
    <DesktopWalletPageHeader />

    <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 clickable-row"
              @click="openDetail(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">{{ t('wallet.no_records') }}</div>
    </section>

    <DesktopTxDetailModal v-model:visible="detailModalVisible" :transaction-id="detailTxId" />
  </div>
</template>

<style scoped>
.type-cell {
  font-weight: 700;
  font-family: var(--font-heading);
  color: var(--text);
}

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