<script setup lang="ts">
import { ref, computed, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { useAdminLocale } from '../../composables/useAdminLocale';
import api from '../../api';
import MatchMarketsPanel from './MatchMarketsPanel.vue';
import type { AdminMatchDetail } from '../match-form';
import AdminSubNav from '../../components/AdminSubNav.vue';

const route = useRoute();
const router = useRouter();
const { t } = useAdminLocale();

const matchId = computed(() => String(route.params.matchId ?? ''));
const loading = ref(false);
const status = ref('DRAFT');
const matchLabel = ref('');

function matchup(home: string, away: string) {
  const h = home.trim();
  const a = away.trim();
  return h && a ? `${h} vs ${a}` : '';
}

async function load() {
  if (!matchId.value) return;
  loading.value = true;
  try {
    const { data } = await api.get(`/admin/matches/${matchId.value}`);
    const detail = data.data as AdminMatchDetail;
    if (detail.isOutright) {
      ElMessage.warning(t('msg.outright_no_edit'));
      router.replace('/matches');
      return;
    }
    status.value = detail.status;
    const zh = matchup(
      detail.homeTeamZh || detail.homeTeamCode || detail.homeTeamEn || '',
      detail.awayTeamZh || detail.awayTeamCode || detail.awayTeamEn || '',
    );
    const en = matchup(
      detail.homeTeamEn || detail.homeTeamCode || detail.homeTeamZh || '',
      detail.awayTeamEn || detail.awayTeamCode || detail.awayTeamZh || '',
    );
    matchLabel.value = zh && en && zh !== en ? `${zh} / ${en}` : zh || en || `#${matchId.value}`;
  } catch (e: unknown) {
    const err = e as { response?: { data?: { error?: string } } };
    ElMessage.error(err.response?.data?.error ?? t('msg.load_failed'));
  } finally {
    loading.value = false;
  }
}

watch(matchId, load, { immediate: true });
</script>

<template>
  <div v-loading="loading" class="match-markets-page">
    <AdminSubNav
      :title="t('matchEditor.section_markets')"
      :subtitle="matchLabel"
    >
      <template #extra>
        <el-tag size="small" type="info">{{ t(`match.status.${status}`) }}</el-tag>
      </template>
    </AdminSubNav>

    <section v-if="matchId" class="panel">
      <MatchMarketsPanel :match-id="matchId" />
    </section>
  </div>
</template>

<style scoped>
.match-markets-page {
  height: 100%;
  min-height: 0;
  padding: 0 4px;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.panel {
  flex: 1;
  min-height: 0;
  background: #ffffff;
  border: 1px solid var(--border);
  border-radius: 10px;
  box-shadow: var(--shadow);
  overflow: hidden;
}
</style>
