<script setup lang="ts">
import { ref } from 'vue';

defineOptions({ name: 'AdminBets' });
import { useStaleListLifecycle } from '../composables/useStaleList';
import api from '../api';
import { formatAmount, formatAmountFull } from '../utils/format-amount';
import {
  betStatusLabel,
  betStatusTagType,
  betTypeLabel,
  betSettlementLabel,
  betResultLabel,
  useBetFilterOptions,
} from '../utils/bet-labels';
import { useAdminLocale } from '../composables/useAdminLocale';
import AdminTableEmpty from '../components/AdminTableEmpty.vue';

const { t, localeTag } = useAdminLocale();
const { statusOptions, typeOptions } = useBetFilterOptions();
import type { BetListRow, BetDetail } from './bet-form';

const bets = ref<BetListRow[]>([]);
const total = ref(0);
const page = ref(1);
const pageSize = ref(10);

const keyword = ref('');
const filterStatus = ref('');
const filterBetType = ref('');
const placedFrom = ref('');
const placedTo = ref('');

const detailVisible = ref(false);
const detail = ref<BetDetail | null>(null);
const detailLoading = ref(false);

async function load() {
  const { data } = await api.get('/admin/bets', {
    params: {
      page: page.value,
      pageSize: pageSize.value,
      keyword: keyword.value.trim() || undefined,
      status: filterStatus.value || undefined,
      betType: filterBetType.value || undefined,
      placedFrom: placedFrom.value || undefined,
      placedTo: placedTo.value || undefined,
    },
  });
  bets.value = data.data.items as BetListRow[];
  total.value = data.data.total;
}

const { loading: listLoading, runLoad } = useStaleListLifecycle(() => bets.value.length > 0, load);

function onPageChange(p: number) {
  page.value = p;
  void runLoad(true);
}

function onSizeChange(size: number) {
  pageSize.value = size;
  page.value = 1;
  void runLoad(true);
}

function resetFilters() {
  keyword.value = '';
  filterStatus.value = '';
  filterBetType.value = '';
  placedFrom.value = '';
  placedTo.value = '';
  page.value = 1;
  void runLoad(true);
}

function betContentCounts(row: BetListRow) {
  const singles = row.betType === 'SINGLE' ? 1 : 0;
  const parlays = row.betType === 'PARLAY' ? 1 : 0;
  return t('bet.content.bet_counts', { singles, parlays });
}

function parentLabel(row: BetListRow) {
  return row.parentUsername ?? t('common.platform_direct');
}

function formatTime(v: string | null | undefined) {
  if (!v) return '—';
  return new Date(v).toLocaleString(localeTag.value, {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
  });
}

function resultStatusLabel(s: string | null | undefined) {
  return betResultLabel(s);
}

async function openDetail(row: BetListRow) {
  detailLoading.value = true;
  detailVisible.value = true;
  detail.value = null;
  try {
    const { data } = await api.get(`/admin/bets/${row.id}`);
    detail.value = data.data as BetDetail;
  } finally {
    detailLoading.value = false;
  }
}
</script>

<template>
  <div class="admin-list-page bets-page">
  <el-card class="filter-card" shadow="never">
    <el-form inline class="bets-filter-form">
      <el-form-item :label="t('common.keyword')">
        <el-input
          v-model="keyword"
          :placeholder="t('bet.filter.keyword_ph')"
          clearable
          style="width: 200px"
          @keyup.enter="load"
        />
      </el-form-item>
      <el-form-item :label="t('common.status')">
        <el-select v-model="filterStatus" :placeholder="t('common.all')" clearable style="width: 120px">
          <el-option
            v-for="o in statusOptions.filter((x) => x.value !== '')"
            :key="o.value"
            :label="o.label"
            :value="o.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('common.type')">
        <el-select v-model="filterBetType" :placeholder="t('common.all')" clearable style="width: 100px">
          <el-option
            v-for="o in typeOptions.filter((x) => x.value !== '')"
            :key="o.value"
            :label="o.label"
            :value="o.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('bet.filter.date_from')">
        <el-date-picker
          v-model="placedFrom"
          type="date"
          value-format="YYYY-MM-DD"
          :placeholder="t('bet.filter.date_start_ph')"
          style="width: 140px"
        />
      </el-form-item>
      <el-form-item :label="t('common.to')">
        <el-date-picker
          v-model="placedTo"
          type="date"
          value-format="YYYY-MM-DD"
          :placeholder="t('bet.filter.date_end_ph')"
          style="width: 140px"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="runLoad(true)">{{ t('common.search') }}</el-button>
        <el-button @click="resetFilters">{{ t('common.reset') }}</el-button>
      </el-form-item>
    </el-form>
  </el-card>

  <el-card v-loading="listLoading" class="data-card" shadow="never">
    <div class="table-wrap">
    <el-table :data="bets" stripe class="bets-table">
      <template #empty>
        <AdminTableEmpty />
      </template>
      <el-table-column type="index" :index="(i: number) => (page - 1) * pageSize + i + 1" :label="t('common.seq')" width="70" align="center" />
      <el-table-column prop="id" :label="t('bet.col.serial')" width="64" align="center" />
      <el-table-column prop="betNo" :label="t('bet.col.bet_no')" min-width="200" show-overflow-tooltip>
        <template #default="{ row }">
          <span class="bet-no">{{ row.betNo }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="username" :label="t('bet.col.player')" min-width="100" show-overflow-tooltip />
      <el-table-column :label="t('bet.col.agent')" min-width="108" show-overflow-tooltip>
        <template #default="{ row }">{{ parentLabel(row) }}</template>
      </el-table-column>
      <el-table-column :label="t('common.type')" min-width="92" align="center">
        <template #default="{ row }">
          <el-tag type="info" size="small" effect="plain">{{ betTypeLabel(row.betType) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column :label="t('bet.col.content')" width="108" align="center">
        <template #default="{ row }">
          <el-tooltip
            v-if="row.selectionSummary"
            :content="row.selectionSummary"
            placement="top"
            :show-after="300"
          >
            <span class="bet-content-summary">{{ betContentCounts(row) }}</span>
          </el-tooltip>
          <span v-else class="bet-content-empty">—</span>
        </template>
      </el-table-column>
      <el-table-column :label="t('bet.col.selection_count')" width="88" align="center">
        <template #default="{ row }">{{ row.selectionCount }}</template>
      </el-table-column>
      <el-table-column :label="t('bet.col.stake')" min-width="100" align="right">
        <template #default="{ row }">
          <el-tooltip :content="formatAmountFull(row.stake)" placement="top">
            <span>{{ formatAmount(row.stake) }}</span>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column :label="t('bet.col.odds')" width="80" align="right">
        <template #default="{ row }">{{ row.totalOdds ?? '—' }}</template>
      </el-table-column>
      <el-table-column :label="t('bet.col.payout')" min-width="100" align="right">
        <template #default="{ row }">
          <el-tooltip :content="formatAmountFull(row.actualReturn)" placement="top">
            <span>{{ formatAmount(row.actualReturn) }}</span>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column :label="t('common.status')" min-width="100" align="center">
        <template #default="{ row }">
          <el-tag :type="betStatusTagType(row.status)" size="small">
            {{ betStatusLabel(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column :label="t('bet.col.cashbacked')" width="88" align="center">
        <template #default="{ row }">
          <el-tag v-if="row.isCashbacked" type="success" size="small" effect="plain">✓</el-tag>
          <span v-else class="bet-content-empty">—</span>
        </template>
      </el-table-column>
      <el-table-column :label="t('bet.col.placed_at')" min-width="168">
        <template #default="{ row }">{{ formatTime(row.placedAt) }}</template>
      </el-table-column>
      <el-table-column :label="t('common.actions')" width="100" fixed="right" align="center">
        <template #default="{ row }">
          <el-button type="primary" link size="small" @click="openDetail(row)">{{ t('common.detail') }}</el-button>
        </template>
      </el-table-column>
    </el-table>
    </div>

    <div class="pager">
      <el-pagination
        v-model:current-page="page"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next"
        background
        @current-change="onPageChange"
        @size-change="onSizeChange"
      />
    </div>
  </el-card>

  <el-dialog v-model="detailVisible" :title="t('bet.dialog.detail')" width="720px" destroy-on-close>
    <div v-loading="detailLoading">
      <template v-if="detail">
        <el-descriptions :column="2" border size="small" class="detail-desc">
          <el-descriptions-item :label="t('bet.col.serial')">{{ detail.id }}</el-descriptions-item>
          <el-descriptions-item :label="t('bet.col.bet_no')">{{ detail.betNo }}</el-descriptions-item>
          <el-descriptions-item :label="t('bet.col.player')">{{ detail.username }}</el-descriptions-item>
          <el-descriptions-item :label="t('bet.col.agent')">{{ parentLabel(detail) }}</el-descriptions-item>
          <el-descriptions-item :label="t('common.type')">{{ betTypeLabel(detail.betType) }}</el-descriptions-item>
          <el-descriptions-item :label="t('bet.field.currency')">{{ detail.currency }}</el-descriptions-item>
          <el-descriptions-item :label="t('bet.col.stake')">
            {{ formatAmountFull(detail.stake) }}
          </el-descriptions-item>
          <el-descriptions-item :label="t('bet.field.total_odds')">{{ detail.totalOdds ?? '—' }}</el-descriptions-item>
          <el-descriptions-item :label="t('bet.field.potential_win')">
            {{ detail.potentialReturn ? formatAmountFull(detail.potentialReturn) : '—' }}
          </el-descriptions-item>
          <el-descriptions-item :label="t('bet.field.actual_payout')">
            {{ formatAmountFull(detail.actualReturn) }}
          </el-descriptions-item>
          <el-descriptions-item :label="t('bet.field.bet_status')">
            <el-tag :type="betStatusTagType(detail.status)" size="small">
              {{ betStatusLabel(detail.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item :label="t('bet.field.settlement_status')">
            {{ betSettlementLabel(detail.settlementStatus) }}
          </el-descriptions-item>
          <el-descriptions-item :label="t('bet.col.placed_at')">{{ formatTime(detail.placedAt) }}</el-descriptions-item>
          <el-descriptions-item :label="t('bet.field.settled_at')">{{ formatTime(detail.settledAt) }}</el-descriptions-item>
          <el-descriptions-item :label="t('bet.col.cashbacked')">
            {{ detail.isCashbacked ? t('common.yes') : t('common.no') }}
          </el-descriptions-item>
          <el-descriptions-item :label="t('bet.field.request_id')" :span="2">{{ detail.requestId }}</el-descriptions-item>
        </el-descriptions>

        <div class="selections-title">{{ t('bet.selections_title', { n: detail.selections.length }) }}</div>
        <el-table :data="detail.selections" size="small" stripe border>
          <el-table-column type="index" label="#" width="44" />
          <el-table-column :label="t('bet.col.match')" min-width="180" show-overflow-tooltip>
            <template #default="{ row }">
              <div class="detail-match-cell">{{ row.matchLabel }}</div>
              <div v-if="row.leagueName" class="detail-league">{{ row.leagueName }}</div>
            </template>
          </el-table-column>
          <el-table-column prop="selectionName" :label="t('bet.col.selection')" min-width="120" show-overflow-tooltip />
          <el-table-column prop="marketType" :label="t('bet.col.market')" width="100" />
          <el-table-column prop="period" :label="t('bet.col.period')" width="72">
            <template #default="{ row }">{{ row.period ?? '—' }}</template>
          </el-table-column>
          <el-table-column prop="odds" :label="t('bet.col.odds')" width="72" align="right" />
          <el-table-column :label="t('bet.col.line')" width="88">
            <template #default="{ row }">
              {{ row.handicapLine ?? row.totalLine ?? '—' }}
            </template>
          </el-table-column>
          <el-table-column :label="t('bet.col.result')" width="72" align="center">
            <template #default="{ row }">{{ resultStatusLabel(row.resultStatus) }}</template>
          </el-table-column>
        </el-table>
      </template>
    </div>
    <template #footer>
      <el-button @click="detailVisible = false">{{ t('common.close') }}</el-button>
    </template>
  </el-dialog>
  </div>
</template>

<style scoped>
.filter-card { margin-bottom: 16px; border-radius: 12px; }
.data-card   { border-radius: 12px; }

.bets-filter-form {
  display: flex;
  flex-wrap: wrap;
  align-items: flex-end;
  gap: 4px 8px;
}
.bets-filter-form :deep(.el-form-item) {
  margin-right: 12px;
  margin-bottom: 8px;
}
.bets-filter-form :deep(.el-form-item__label) {
  padding-bottom: 0;
}

.bets-table {
  min-width: 1380px;
}

.bet-content-summary {
  font-size: 13px;
  color: #ccc;
  white-space: nowrap;
}

.bet-content-empty {
  color: #666;
}

.detail-match-cell {
  line-height: 1.35;
}

.detail-league {
  margin-top: 2px;
  font-size: 11px;
  color: #888;
}
.bet-no {
  font-size: 12px;
  color: #ccc;
  font-family: ui-monospace, monospace;
  white-space: nowrap;
}
.pager { display: flex; justify-content: flex-end; margin-top: 16px; }
.detail-desc { margin-bottom: 16px; }
.selections-title {
  font-size: 13px;
  font-weight: 700;
  color: #aaa;
  margin-bottom: 10px;
}

.filter-card,
.data-card {
  border-radius: 8px;
}

.bet-content-summary,
.bet-no,
.selections-title {
  color: var(--text);
}

.bet-content-empty,
.detail-league {
  color: var(--text-muted);
}

@media (max-width: 760px) {
  .bets-filter-form {
    align-items: stretch;
  }

  .bets-filter-form :deep(.el-form-item) {
    margin-right: 0;
  }
}
</style>
