<script setup lang="ts">
import { ref, computed, onMounted, onBeforeUnmount } from 'vue';
import { useRoute } from 'vue-router';
import { useAdminLocale } from '../composables/useAdminLocale';
import { resolveFormError } from '../i18n/form-validation';
import api from '../api';
import { ElMessage } from 'element-plus';
import LeagueMatchesPanel from './matches/LeagueMatchesPanel.vue';
import MatchesSubNav from '../components/MatchesSubNav.vue';
import CountryFlagSelect from '../components/outright/CountryFlagSelect.vue';
import { getBuiltinCountry } from '../data/builtinCountries';
import {
  readMatchesListUiState,
  writeMatchesListUiState,
} from '../utils/matchesListState';
import { formatAmount } from '../utils/format-amount';
import {
  emptyMatchForm,
  buildPlatformPayload,
  fillBuiltinTeam,
  clearBuiltinTeam,
  type MatchCreateForm,
} from './match-form';

const { t } = useAdminLocale();
const route = useRoute();
const leagues = ref<unknown[]>([]);
const total = ref(0);
const page = ref(1);
const pageSize = ref(10);
const filterStatus = ref('');
const keyword = ref('');
const expandedRowKeys = ref<string[]>([]);

const createLeagueVisible = ref(false);
const createLeagueLoading = ref(false);
const leagueForm = ref({ leagueEn: '', leagueZh: '', leagueMs: '', logoUrl: '' });

const createVisible = ref(false);
const importVisible = ref(false);
const createLoading = ref(false);
const importLoading = ref(false);
const importJson = ref('');
const form = ref<MatchCreateForm>(emptyMatchForm());
const createUnderLeagueLabel = ref('');

const isFixtureCreate = computed(() => !!form.value.leagueId.trim());

function persistListUiState() {
  writeMatchesListUiState({
    expandedLeagueIds: [...expandedRowKeys.value],
    page: page.value,
    pageSize: pageSize.value,
    filterStatus: filterStatus.value,
    keyword: keyword.value,
  });
}

function applyExpandedFromSaved(savedIds: string[]) {
  const allowed = new Set(leagues.value.map((row) => leagueId(row)));
  expandedRowKeys.value = savedIds.filter((id) => allowed.has(id));
}

type LoadOptions = { restoreExpand?: boolean; keepExpand?: boolean };

async function load(options: LoadOptions = {}) {
  const saved = options.restoreExpand ? readMatchesListUiState() : null;
  if (saved) {
    page.value = saved.page;
    pageSize.value = saved.pageSize;
    filterStatus.value = saved.filterStatus;
    keyword.value = saved.keyword;
  }

  const { data } = await api.get('/admin/leagues', {
    params: {
      page: page.value,
      pageSize: pageSize.value,
      status: filterStatus.value || undefined,
      keyword: keyword.value.trim() || undefined,
    },
  });
  leagues.value = data.data.items;
  total.value = data.data.total;

  if (options.restoreExpand && saved) {
    applyExpandedFromSaved(saved.expandedLeagueIds);
  } else if (!options.keepExpand) {
    expandedRowKeys.value = [];
  } else {
    applyExpandedFromSaved(expandedRowKeys.value);
  }
  persistListUiState();
}

function onSearch() {
  page.value = 1;
  expandedRowKeys.value = [];
  load();
}

onMounted(() => {
  const qStatus = route.query.status;
  if (typeof qStatus === 'string' && qStatus.trim()) {
    filterStatus.value = qStatus.trim();
    page.value = 1;
    load();
    return;
  }
  load({ restoreExpand: true });
});
onBeforeUnmount(persistListUiState);

function onPageChange(p: number) {
  page.value = p;
  load({ keepExpand: true });
}

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

function openCreateLeague() {
  leagueForm.value = { leagueEn: '', leagueZh: '', leagueMs: '', logoUrl: '' };
  createLeagueVisible.value = true;
}

async function submitCreateLeague() {
  const { leagueEn, leagueZh, leagueMs, logoUrl } = leagueForm.value;
  if (!leagueZh.trim() && !leagueEn.trim()) {
    ElMessage.warning(t('err.league_required'));
    return;
  }
  createLeagueLoading.value = true;
  try {
    await api.post('/admin/leagues', {
      leagueEn: leagueEn.trim(),
      leagueZh: leagueZh.trim(),
      leagueMs: leagueMs.trim() || undefined,
      logoUrl: logoUrl.trim() || undefined,
    });
    ElMessage.success(t('msg.league_created'));
    createLeagueVisible.value = false;
    load({ keepExpand: true });
  } catch (e: unknown) {
    const err = e as { response?: { data?: { error?: string } } };
    ElMessage.error(err.response?.data?.error ?? t('msg.create_failed'));
  } finally {
    createLeagueLoading.value = false;
  }
}

function onTeamCodeChange(side: 'home' | 'away', code: string) {
  if (!code?.trim()) {
    clearBuiltinTeam(form.value, side);
    return;
  }
  const country = getBuiltinCountry(code);
  if (country) fillBuiltinTeam(form.value, side, country);
}

function openCreateFixture(leagueRow: unknown) {
  const r = rowOf(leagueRow);
  form.value = emptyMatchForm();
  form.value.leagueId = String(r.id ?? '');
  form.value.leagueEn = String(r.leagueEn ?? '');
  form.value.leagueZh = String(r.leagueZh ?? '');
  form.value.leagueMs = String(r.leagueMs ?? '');
  createUnderLeagueLabel.value = leagueTitle(leagueRow);
  createVisible.value = true;
}

function openImport() {
  importJson.value = '';
  importVisible.value = true;
}

async function submitCreate() {
  let payload: ReturnType<typeof buildPlatformPayload>;
  try {
    payload = buildPlatformPayload(form.value);
  } catch (e) {
    ElMessage.warning(resolveFormError(e, t));
    return;
  }
  createLoading.value = true;
  try {
    await api.post('/admin/matches', payload);
    ElMessage.success(t('msg.match_created_draft'));
    createUnderLeagueLabel.value = '';
    createVisible.value = false;
    const lid = form.value.leagueId.trim();
    await load({ keepExpand: true });
    if (lid && !expandedRowKeys.value.includes(lid)) {
      expandedRowKeys.value = [...expandedRowKeys.value, lid];
      persistListUiState();
    }
  } catch (e: unknown) {
    const err = e as { response?: { data?: { error?: string } } };
    ElMessage.error(err.response?.data?.error ?? t('msg.create_failed'));
  } finally {
    createLoading.value = false;
  }
}

async function submitImport() {
  let payload: unknown;
  try {
    payload = JSON.parse(importJson.value);
  } catch {
    ElMessage.error(t('msg.invalid_json'));
    return;
  }
  importLoading.value = true;
  try {
    const { data } = await api.post('/admin/matches/import', payload);
    const r = data.data as {
      imported: number;
      skipped: number;
      failed: number;
      total: number;
    };
    ElMessage.success(
      t('msg.import_done', {
        imported: r.imported,
        skipped: r.skipped,
        failed: r.failed,
        total: r.total,
      }),
    );
    importVisible.value = false;
    load({ keepExpand: true });
  } catch (e: unknown) {
    const err = e as { response?: { data?: { error?: string } } };
    ElMessage.error(err.response?.data?.error ?? t('msg.import_failed'));
  } finally {
    importLoading.value = false;
  }
}

function onExpandChange(_row: unknown, expanded: unknown[]) {
  expandedRowKeys.value = expanded.map((r) => leagueId(r));
  persistListUiState();
}

function onRowClick(row: unknown, _column: unknown, event: MouseEvent) {
  if ((event.target as HTMLElement).closest('.el-table__expand-icon')) return;
  const id = leagueId(row);
  expandedRowKeys.value = expandedRowKeys.value.includes(id) ? [] : [id];
  persistListUiState();
}

function rowClassName() {
  return 'row-expandable';
}

function rowOf(row: unknown) {
  return row as Record<string, unknown>;
}
function leagueId(row: unknown) {
  return String(rowOf(row).id ?? '');
}
function leagueTitle(row: unknown) {
  const r = rowOf(row);
  const zh = String(r.leagueZh ?? '').trim();
  const en = String(r.leagueEn ?? '').trim();
  return zh || en || String(r.code ?? '—');
}
function leagueNameZh(row: unknown) {
  const zh = String(rowOf(row).leagueZh ?? '').trim();
  return zh || '—';
}
function leagueNameEn(row: unknown) {
  const en = String(rowOf(row).leagueEn ?? '').trim();
  return en || '—';
}
function leagueMatchCount(row: unknown) {
  return Number(rowOf(row).matchCount ?? 0);
}

function leagueBetStats(row: unknown) {
  return rowOf(row).betStats as
    | { betCount?: number; totalStake?: string; pendingCount?: number }
    | undefined;
}

function leagueBetCount(row: unknown) {
  return Number(leagueBetStats(row)?.betCount ?? 0);
}

function leagueTotalStake(row: unknown) {
  return formatAmount(String(leagueBetStats(row)?.totalStake ?? '0'));
}

function leaguePendingBets(row: unknown) {
  return Number(leagueBetStats(row)?.pendingCount ?? 0);
}
function isLeagueExpanded(id: string) {
  return expandedRowKeys.value.includes(id);
}

</script>

<template>
  <div class="admin-list-page matches-page">
  <div class="list-chrome">
    <div class="list-chrome__row">
      <div class="list-chrome__left">
        <MatchesSubNav embedded />
        <div class="list-chrome__filters">
          <div class="list-chrome__field">
            <span class="list-chrome__label">{{ t('common.keyword') }}</span>
            <el-input
              v-model="keyword"
              :placeholder="t('match.filter.keyword_ph')"
              clearable
              style="width: 200px"
              @keyup.enter="load"
            />
          </div>
          <div class="list-chrome__field">
            <span class="list-chrome__label">{{ t('common.status') }}</span>
            <el-select v-model="filterStatus" :placeholder="t('common.all')" clearable style="width: 120px">
              <el-option :label="t('match.status.DRAFT')" value="DRAFT" />
              <el-option :label="t('match.status.PUBLISHED')" value="PUBLISHED" />
              <el-option :label="t('match.status.CLOSED')" value="CLOSED" />
              <el-option :label="t('match.status.PENDING_SETTLEMENT')" value="PENDING_SETTLEMENT" />
              <el-option :label="t('match.status.SETTLED')" value="SETTLED" />
            </el-select>
          </div>
          <el-button type="primary" class="list-chrome__submit" @click="onSearch">
            {{ t('common.search') }}
          </el-button>
        </div>
      </div>
      <div class="list-chrome__actions">
        <el-button @click="openImport">{{ t('common.import') }}</el-button>
        <el-button type="primary" @click="openCreateLeague">{{ t('match.create_btn') }}</el-button>
      </div>
    </div>
    <p v-if="filterStatus" class="list-hint">{{ t('match.filter.status_hint') }}</p>
  </div>

  <section class="list-panel">
    <p class="list-hint">{{ t('match.expand_league_hint') }}</p>
    <div class="table-wrap">
    <el-table
      :data="leagues"
      stripe
      row-key="id"
      :expand-row-keys="expandedRowKeys"
      :row-class-name="rowClassName"
      @expand-change="onExpandChange"
      @row-click="onRowClick"
    >
      <el-table-column type="expand" width="40">
        <template #default="{ row }">
          <template v-if="isLeagueExpanded(leagueId(row))">
            <LeagueMatchesPanel
              :league-id="leagueId(row)"
              :filter-status="filterStatus"
              :keyword="keyword"
              @changed="() => load({ keepExpand: true })"
              @add-match="openCreateFixture(row)"
            />
          </template>
        </template>
      </el-table-column>
      <el-table-column prop="id" label="ID" width="72" />
      <el-table-column :label="t('match.col.league')" width="148" show-overflow-tooltip>
        <template #default="{ row }">
          <div class="league-cell">
            <img
              v-if="rowOf(row).logoUrl"
              :src="String(rowOf(row).logoUrl)"
              alt=""
              class="league-logo"
            />
            <span class="matchup-link">{{ leagueNameZh(row) }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column :label="t('match.col.league_en')" width="180" show-overflow-tooltip>
        <template #default="{ row }">
          <span class="league-en">{{ leagueNameEn(row) }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="t('match.col.fixture_count')" width="88" align="center">
        <template #default="{ row }">{{ leagueMatchCount(row) }}</template>
      </el-table-column>
      <el-table-column :label="t('match.col.bet_count')" width="72" align="center">
        <template #default="{ row }">
          <span :class="{ 'bet-stat-active': leagueBetCount(row) > 0 }">{{ leagueBetCount(row) }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="t('match.col.total_stake')" width="108" align="right">
        <template #default="{ row }">{{ leagueTotalStake(row) }}</template>
      </el-table-column>
      <el-table-column :label="t('match.col.pending_bets')" width="80" align="center">
        <template #default="{ row }">
          <el-tag v-if="leaguePendingBets(row) > 0" type="warning" size="small" effect="plain">
            {{ leaguePendingBets(row) }}
          </el-tag>
          <span v-else class="bet-stat-zero">0</span>
        </template>
      </el-table-column>
      <el-table-column :label="t('match.col.league_code')" width="140" show-overflow-tooltip>
        <template #default="{ row }">{{ rowOf(row).code }}</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>
  </section>

  <el-dialog v-model="createLeagueVisible" :title="t('match.dialog.create_league')" width="520px" destroy-on-close>
    <el-form label-width="96px">
      <el-form-item :label="t('match.field.league_zh')">
        <el-input v-model="leagueForm.leagueZh" :placeholder="t('match.ph.league_zh')" />
      </el-form-item>
      <el-form-item :label="t('match.field.league_en')">
        <el-input v-model="leagueForm.leagueEn" :placeholder="t('match.ph.league_en')" />
      </el-form-item>
      <el-form-item :label="t('match.field.league_ms')">
        <el-input v-model="leagueForm.leagueMs" :placeholder="t('match.ph.league_ms')" />
      </el-form-item>
      <el-form-item :label="t('match.field.league_logo')">
        <el-input v-model="leagueForm.logoUrl" :placeholder="t('matchEditor.ph.logo_url')" />
      </el-form-item>
      <p class="field-hint">{{ t('match.hint.create_league') }}</p>
    </el-form>
    <template #footer>
      <el-button @click="createLeagueVisible = false">{{ t('common.cancel') }}</el-button>
      <el-button type="primary" :loading="createLeagueLoading" @click="submitCreateLeague">
        {{ t('user.btn.create') }}
      </el-button>
    </template>
  </el-dialog>

  <el-dialog
    v-model="createVisible"
    :title="t('match.dialog.create_fixture')"
    width="560px"
    destroy-on-close
  >
    <el-form label-width="96px">
      <el-form-item v-if="isFixtureCreate" :label="t('match.col.league')">
        <span class="league-readonly">{{ createUnderLeagueLabel }}</span>
      </el-form-item>
      <template v-else>
        <el-form-item :label="t('match.field.league_en')">
          <el-input v-model="form.leagueEn" :placeholder="t('match.ph.league_en')" />
        </el-form-item>
        <el-form-item :label="t('match.field.league_zh')">
          <el-input v-model="form.leagueZh" :placeholder="t('match.ph.league_zh')" />
        </el-form-item>
      </template>
      <el-form-item :label="t('match.field.kickoff')" required>
        <el-date-picker
          v-model="form.startTime"
          type="datetime"
          value-format="YYYY-MM-DDTHH:mm:ss"
          :placeholder="t('matchEditor.ph.kickoff')"
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item :label="t('match.field.home_team')" required>
        <CountryFlagSelect
          v-model="form.homeTeamCode"
          size="default"
          class="team-country-select"
          @update:model-value="onTeamCodeChange('home', $event)"
        />
      </el-form-item>
      <el-form-item :label="t('match.field.away_team')" required>
        <CountryFlagSelect
          v-model="form.awayTeamCode"
          size="default"
          class="team-country-select"
          @update:model-value="onTeamCodeChange('away', $event)"
        />
      </el-form-item>
      <el-form-item :label="t('match.field.featured')">
        <el-switch v-model="form.isHot" />
      </el-form-item>
      <p class="field-hint">{{ t('match.hint.create_draft') }}</p>
    </el-form>
    <template #footer>
      <el-button @click="createVisible = false">{{ t('common.cancel') }}</el-button>
      <el-button type="primary" :loading="createLoading" @click="submitCreate">{{ t('user.btn.create') }}</el-button>
    </template>
  </el-dialog>

  <el-dialog v-model="importVisible" :title="t('match.dialog.import')" width="640px" destroy-on-close>
    <p class="dialog-hint">{{ t('match.import_hint') }}</p>
    <el-input
      v-model="importJson"
      type="textarea"
      :rows="14"
      :placeholder="t('match.import_json_ph')"
    />
    <template #footer>
      <el-button @click="importVisible = false">{{ t('common.cancel') }}</el-button>
      <el-button type="primary" :loading="importLoading" @click="submitImport">{{ t('match.import_start') }}</el-button>
    </template>
  </el-dialog>
  </div>
</template>

<style scoped>
.dialog-hint {
  font-size: 13px;
  color: #666;
  margin: 0 0 12px;
  line-height: 1.5;
}
.team-country-select {
  width: 100%;
}

.dialog-hint code {
  color: #aaa;
}
.field-hint {
  font-size: 12px;
  color: #666;
  margin: 0;
  line-height: 1.5;
}
.edit-hint {
  margin-bottom: 16px;
}

/* 列表表格随内容增高，滚动交给外层 table-wrap（仅赛事行） */
.matches-page .table-wrap .el-table {
  height: auto !important;
}
.matches-page .table-wrap :deep(.el-table__header),
.matches-page .table-wrap :deep(.el-table__body) {
  width: 100% !important;
}

.matches-page :deep(.el-table__expanded-cell) {
  padding: 0 !important;
  background: #0a0a0a;
}

.list-panel :deep(.row-expandable) {
  cursor: pointer;
}

.list-panel :deep(.row-no-expand .el-table__expand-icon) {
  visibility: hidden;
  pointer-events: none;
}

.matchup-link {
  color: var(--green-text);
}
.bet-stat-active {
  color: var(--green-text);
  font-weight: 600;
}
.bet-stat-zero {
  color: #555;
}

.league-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.league-logo {
  width: 28px;
  height: 28px;
  object-fit: contain;
  flex-shrink: 0;
}

.league-en {
  color: #aaa;
  font-size: 13px;
}

.league-readonly {
  color: var(--green-text);
  font-weight: 500;
}

:deep(.logo-url-field) {
  width: 100%;
}
</style>
