<script setup lang="ts">
import { ref, onMounted, onActivated } from 'vue';
import { useI18n } from 'vue-i18n';
import { RouterLink } from 'vue-router';
import api from '../../api';
import GoldSpinner from '../../components/GoldSpinner.vue';
import Pagination from '../../components/desktop/Pagination.vue';
import { type BetHistoryItem } from '../../components/BetHistoryCard.vue';
import { useOnLocaleChange } from '../../composables/useOnLocaleChange';

const COL_COUNT = 8;

const { t } = useI18n();

const items = ref<BetHistoryItem[]>([]);
const total = ref(0);
const page = ref(1);
const pageSize = ref(20);
const loading = ref(false);
const initialLoading = ref(true);
const statusFilter = ref('');

const STATUS_FILTERS = [
  { key: '', label: 'history.filter_all' },
  { key: 'WON', label: 'history.filter_won' },
  { key: 'LOST', label: 'history.filter_lost' },
  { key: 'PENDING', label: 'history.filter_pending' },
] as const;

const PUSH_FILTER = { key: 'PUSH', label: 'history.filter_push' } as const;

async function loadPage(p: number) {
  if (loading.value) return;
  loading.value = true;
  try {
    const params: Record<string, unknown> = { page: p, pageSize: pageSize.value };
    if (statusFilter.value) params.status = statusFilter.value;
    const { data } = await api.get('/player/bets', { params });
    const result = data.data ?? { items: [], total: 0, pageSize: pageSize.value };
    total.value = result.total ?? 0;
    items.value = result.items ?? [];
    page.value = p;
  } finally {
    loading.value = false;
    initialLoading.value = false;
  }
}

function changeFilter(key: string) {
  if (statusFilter.value === key) return;
  statusFilter.value = key;
  page.value = 1;
  initialLoading.value = true;
  void loadPage(1);
}

useOnLocaleChange(() => {
  page.value = 1;
  initialLoading.value = true;
  void loadPage(1);
});

onActivated(() => { void loadPage(page.value); });
onMounted(() => { void loadPage(1); });

function statusClass(status: string) {
  const map: Record<string, string> = {
    WON: 'status-won',
    LOST: 'status-lost',
    PENDING: 'status-pending',
    PUSH: 'status-push',
    CANCELLED: 'status-cancelled',
  };
  return map[status?.toUpperCase()] ?? 'status-default';
}

function statusLabel(status: string) {
  const map: Record<string, string> = {
    WON: t('history.filter_won'),
    LOST: t('history.filter_lost'),
    PENDING: t('history.filter_pending'),
    PUSH: t('history.filter_push'),
    CANCELLED: t('common.cancelled'),
  };
  return map[status?.toUpperCase()] ?? status;
}
</script>

<template>
  <div class="desktop-records-page">
    <header class="desktop-records-header">
      <div class="desktop-records-header-main">
        <div class="desktop-records-filter-groups">
          <div class="desktop-records-filter-group">
            <span class="desktop-records-filter-group-label">{{ t('history.filter_status_group') }}</span>
            <div class="desktop-records-filter-bar">
              <button
                v-for="f in STATUS_FILTERS"
                :key="f.key"
                type="button"
                class="desktop-records-filter-chip"
                :class="{ active: statusFilter === f.key }"
                @click="changeFilter(f.key)"
              >
                {{ t(f.label) }}
              </button>
            </div>
          </div>
          <span class="desktop-records-filter-divider" aria-hidden="true" />
          <div class="desktop-records-filter-group">
            <span class="desktop-records-filter-group-label">{{ t('history.filter_push_group') }}</span>
            <div class="desktop-records-filter-bar">
              <button
                type="button"
                class="desktop-records-filter-chip"
                :class="{ active: statusFilter === PUSH_FILTER.key }"
                :title="t('history.filter_push_hint')"
                @click="changeFilter(PUSH_FILTER.key)"
              >
                {{ t(PUSH_FILTER.label) }}
              </button>
            </div>
          </div>
        </div>
      </div>
    </header>

    <section class="desktop-records-panel">
      <div class="desktop-records-table-wrap">
        <table class="desktop-records-table">
          <thead>
            <tr>
              <th>{{ t('bet.bet_no') }}</th>
              <th>{{ t('bet.match') }}</th>
              <th>{{ t('bet.selection') }}</th>
              <th class="num-th">{{ t('bet.odds') }}</th>
              <th class="num-th">{{ t('bet.stake') }}</th>
              <th class="num-th">{{ t('bet.potential_payout') }}</th>
              <th>{{ t('common.status') }}</th>
              <th>{{ t('bet.placed_at') }}</th>
            </tr>
          </thead>
          <tbody>
            <tr v-if="initialLoading || 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="bet in items" :key="bet.betNo" class="hover-row">
                <td>
                  <RouterLink :to="`/bets/${bet.betNo}`" class="link-cell">{{ bet.betNo }}</RouterLink>
                </td>
                <td>{{ bet.matchTitle || '-' }}</td>
                <td class="muted-cell">{{ bet.pickLabel || '-' }}</td>
                <td class="num-cell">{{ bet.totalOdds ?? '-' }}</td>
                <td class="num-cell">{{ bet.stake }}</td>
                <td class="num-cell">{{ bet.potentialReturn ?? '-' }}</td>
                <td>
                  <span class="desktop-records-status" :class="statusClass(bet.status)">
                    {{ statusLabel(bet.status) }}
                  </span>
                </td>
                <td class="date-cell">{{ bet.placedAt ? new Date(bet.placedAt).toLocaleString() : '-' }}</td>
              </tr>
            </template>
            <tr v-else class="state-row">
              <td :colspan="COL_COUNT" class="desktop-records-table-empty">
                {{ t('history.empty') }}
              </td>
            </tr>
          </tbody>
        </table>
      </div>
      <div v-if="!initialLoading && !loading && total > 0" class="desktop-records-pagination">
        <Pagination
          v-model="page"
          v-model:pageSize="pageSize"
          :total="total"
          @change="loadPage"
        />
      </div>
    </section>
  </div>
</template>

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