<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 DesktopRechargeDetailModal from '../../components/desktop/DesktopRechargeDetailModal.vue';
import { formatMoney } from '../../utils/localeDisplay';
import { enrichDepositOrder, findDepositOrderById, type PlayerDepositOrder } from '../../utils/depositOrderLookup';

const COL_COUNT = 5;

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

const detailModalVisible = ref(false);
const detailOrder = ref<PlayerDepositOrder | null>(null);

async function openDetail(order: PlayerDepositOrder) {
  detailOrder.value = await enrichDepositOrder(order);
  detailModalVisible.value = true;
}

async function openDetailFromQuery() {
  const orderId = route.query.orderId;
  if (typeof orderId !== 'string' || !orderId) return;

  const existing = items.value.find((order) => order.id === orderId);
  const order = existing ?? await findDepositOrderById(orderId);
  if (order) openDetail(order);

  const { orderId: _removed, ...rest } = route.query;
  void router.replace({ path: route.path, query: rest });
}

watch(() => route.query.orderId, () => {
  void openDetailFromQuery();
});

watch(detailModalVisible, (visible) => {
  if (!visible) detailOrder.value = null;
});

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

async function loadPage(p: number) {
  loading.value = true;
  try {
    const { data } = await api.get('/player/deposit-orders', { 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(async () => {
  await loadPage(1);
  await openDetailFromQuery();
});
onActivated(async () => {
  await loadPage(page.value);
  await openDetailFromQuery();
});

function methodLabel(order: PlayerDepositOrder) {
  if (order.methodType === 'USDT') return 'USDT';
  return order.paymentMethodName || order.bankName || order.methodType || '-';
}

function statusClass(status: string) {
  const map: Record<string, string> = {
    APPROVED: 'status-won',
    REJECTED: 'status-lost',
    PENDING: 'status-pending',
  };
  return map[status?.toUpperCase()] ?? 'status-default';
}

function statusLabel(status: string) {
  const s = status?.toUpperCase();
  if (s === 'APPROVED') return t('recharge.status_approved');
  if (s === 'REJECTED') return t('recharge.status_rejected');
  return t('recharge.status_pending');
}
</script>

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

    <section class="desktop-records-panel">
      <div class="desktop-records-table-wrap">
        <table class="desktop-records-table">
          <thead>
            <tr>
              <th>{{ t('recharge.order_no') }}</th>
              <th>{{ t('recharge.method') }}</th>
              <th class="num-th">{{ t('wallet.amount') }}</th>
              <th>{{ t('common.status') }}</th>
              <th>{{ t('wallet.time') }}</th>
            </tr>
          </thead>
          <tbody>
            <tr v-if="loading" class="state-row">
              <td :colspan="COL_COUNT">
                <div class="desktop-records-loading-cell">
                  <GoldSpinner :size="36" />
                </div>
              </td>
            </tr>
            <template v-else-if="items.length">
              <tr
                v-for="order in items"
                :key="order.id"
                class="hover-row clickable-row"
                @click="openDetail(order)"
              >
                <td class="id-cell">{{ order.orderNo || order.id }}</td>
                <td>{{ methodLabel(order) }}</td>
                <td class="num-cell">{{ formatMoney(order.amount, locale) }}</td>
                <td>
                  <span class="desktop-records-status" :class="statusClass(order.status)">
                    {{ statusLabel(order.status) }}
                  </span>
                </td>
                <td class="date-cell">{{ new Date(order.createdAt).toLocaleString() }}</td>
              </tr>
            </template>
            <tr v-else class="state-row">
              <td :colspan="COL_COUNT" class="desktop-records-table-empty">
                {{ t('recharge.no_orders') }}
              </td>
            </tr>
          </tbody>
        </table>
      </div>
      <div v-if="!loading && total > 0" class="desktop-records-pagination">
        <Pagination
          v-model="page"
          v-model:pageSize="pageSize"
          :total="total"
          @change="loadPage"
        />
      </div>
    </section>

    <DesktopRechargeDetailModal v-model:visible="detailModalVisible" :order="detailOrder" />
  </div>
</template>
