<script setup lang="ts">
import { ref, watch, computed } from 'vue';
import { ElMessage } from 'element-plus';
import api from '../api';
import { useAdminLocale } from '../composables/useAdminLocale';

type LeagueBlockingMatch = {
  id: string;
  status: string;
  isOutright: boolean;
  title: string;
  pendingCount: number;
};

type LeagueArchivePreview = {
  leagueId: string;
  canArchive: boolean;
  blockingMatches: LeagueBlockingMatch[];
  totalPendingBets: number;
};

const props = defineProps<{
  modelValue: boolean;
  leagueId: string;
  leagueName?: string;
}>();

const emit = defineEmits<{
  'update:modelValue': [value: boolean];
  archived: [];
}>();

const { t } = useAdminLocale();
const loading = ref(false);
const submitting = ref(false);
const preview = ref<LeagueArchivePreview | null>(null);

const displayName = computed(() => props.leagueName || props.leagueId);

watch(
  () => [props.modelValue, props.leagueId] as const,
  ([open]) => {
    if (open && props.leagueId) void loadPreview();
  },
);

function close() {
  emit('update:modelValue', false);
}

async function loadPreview() {
  loading.value = true;
  preview.value = null;
  try {
    const { data } = await api.get(`/admin/leagues/${props.leagueId}/archive-preview`);
    preview.value = data.data as LeagueArchivePreview;
  } catch (e: unknown) {
    const err = e as { response?: { data?: { error?: string } } };
    ElMessage.error(err.response?.data?.error ?? t('msg.load_failed'));
    close();
  } finally {
    loading.value = false;
  }
}

async function confirmArchive() {
  if (!preview.value?.canArchive) return;
  submitting.value = true;
  try {
    await api.post(`/admin/leagues/${props.leagueId}/archive`);
    ElMessage.success(t('archive.league_done'));
    close();
    emit('archived');
  } catch (e: unknown) {
    const err = e as { response?: { data?: { error?: string } } };
    ElMessage.error(err.response?.data?.error ?? t('msg.delete_failed'));
  } finally {
    submitting.value = false;
  }
}

function matchTypeLabel(row: LeagueBlockingMatch) {
  return row.isOutright ? t('nav.outrights') : t('match.col.matchup');
}
</script>

<template>
  <el-dialog
    :model-value="modelValue"
    :title="t('archive.league_title')"
    width="640px"
    destroy-on-close
    @update:model-value="emit('update:modelValue', $event)"
  >
    <div v-loading="loading">
      <p class="archive-target">{{ t('archive.league_target', { name: displayName }) }}</p>
      <p class="archive-hint">{{ t('archive.league_hint') }}</p>
      <template v-if="preview">
        <el-alert
          v-if="!preview.canArchive"
          type="warning"
          :closable="false"
          show-icon
          class="archive-alert"
        >
          {{ t('archive.league_blocked') }}
        </el-alert>
        <el-table
          v-if="preview.blockingMatches.length"
          :data="preview.blockingMatches"
          size="small"
          stripe
          class="blocking-table"
        >
          <el-table-column prop="title" :label="t('match.col.matchup')" min-width="160" />
          <el-table-column :label="t('common.type')" width="88">
            <template #default="{ row }">{{ matchTypeLabel(row) }}</template>
          </el-table-column>
          <el-table-column :label="t('common.status')" width="100">
            <template #default="{ row }">
              <el-tag size="small" type="info">{{ row.status }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column :label="t('match.col.pending_bets')" width="88" align="center">
            <template #default="{ row }">{{ row.pendingCount }}</template>
          </el-table-column>
        </el-table>
        <p v-else-if="preview.canArchive" class="archive-ok">{{ t('archive.league_ready') }}</p>
      </template>
    </div>
    <template #footer>
      <el-button @click="close">{{ t('common.cancel') }}</el-button>
      <el-button
        type="danger"
        :disabled="!preview?.canArchive"
        :loading="submitting"
        @click="confirmArchive"
      >
        {{ t('archive.league_confirm') }}
      </el-button>
    </template>
  </el-dialog>
</template>

<style scoped>
.archive-target {
  margin: 0 0 8px;
  font-weight: 600;
}
.archive-hint {
  margin: 0 0 12px;
  font-size: 12px;
  color: var(--el-text-color-secondary);
}
.archive-alert {
  margin-bottom: 12px;
}
.blocking-table {
  margin-bottom: 8px;
}
.archive-ok {
  margin: 0;
  color: var(--el-color-success);
  font-size: 13px;
}
</style>
