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

type MatchArchiveWarning = 'PENDING_BETS' | 'UNSETTLED_MATCH' | 'PREVIEW_BATCH';

type MatchArchivePreview = {
  matchId: string;
  matchStatus: string;
  isOutright: boolean;
  title: string;
  pendingBetCount: number;
  pendingStake: string;
  hasPreviewSettlementBatch: boolean;
  requiresForce: boolean;
  warnings: MatchArchiveWarning[];
};

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

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

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

const displayTitle = computed(() => props.title || preview.value?.title || props.matchId);

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

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

async function loadPreview() {
  loading.value = true;
  preview.value = null;
  try {
    const { data } = await api.get(`/admin/matches/${props.matchId}/archive-preview`);
    preview.value = data.data as MatchArchivePreview;
    refundPendingBets.value = (preview.value.pendingBetCount ?? 0) > 0;
  } 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(force: boolean) {
  if (!preview.value) return;
  submitting.value = true;
  try {
    const { data } = await api.post(`/admin/matches/${props.matchId}/archive`, {
      force,
      refundPendingBets: refundPendingBets.value,
    });
    const voided = (data.data as { voidedCount?: number })?.voidedCount ?? 0;
    ElMessage.success(
      voided > 0 ? t('archive.msg_done_refund', { n: voided }) : t('archive.msg_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 warningLabel(code: MatchArchiveWarning) {
  return t(`archive.warning.${code}`);
}
</script>

<template>
  <el-dialog
    :model-value="modelValue"
    :title="t('archive.match_title')"
    width="520px"
    destroy-on-close
    @update:model-value="emit('update:modelValue', $event)"
  >
    <div v-loading="loading">
      <p class="archive-target">{{ t('archive.target', { title: displayTitle }) }}</p>
      <template v-if="preview">
        <ul v-if="preview.warnings.length" class="archive-warnings">
          <li v-for="w in preview.warnings" :key="w">{{ warningLabel(w) }}</li>
        </ul>
        <p v-if="preview.pendingBetCount > 0" class="archive-stat">
          {{
            t('archive.pending_summary', {
              count: preview.pendingBetCount,
              stake: formatAmount(preview.pendingStake),
            })
          }}
        </p>
        <p class="archive-hint">{{ t('archive.soft_delete_hint') }}</p>
        <el-checkbox
          v-if="preview.pendingBetCount > 0"
          v-model="refundPendingBets"
          class="archive-refund"
        >
          {{ t('archive.refund_pending') }}
        </el-checkbox>
        <p v-if="preview.pendingBetCount > 0 && refundPendingBets" class="archive-parlay-hint">
          {{ t('archive.parlay_void_hint') }}
        </p>
      </template>
    </div>
    <template #footer>
      <el-button @click="close">{{ t('common.cancel') }}</el-button>
      <template v-if="preview">
        <el-button
          v-if="!preview.requiresForce"
          type="danger"
          :loading="submitting"
          @click="confirmArchive(false)"
        >
          {{ t('common.delete') }}
        </el-button>
        <el-button
          v-else
          type="danger"
          :loading="submitting"
          @click="confirmArchive(true)"
        >
          {{ t('archive.force_delete') }}
        </el-button>
      </template>
    </template>
  </el-dialog>
</template>

<style scoped>
.archive-target {
  margin: 0 0 12px;
  font-weight: 600;
}
.archive-warnings {
  margin: 0 0 12px;
  padding-left: 18px;
  color: var(--el-color-warning);
}
.archive-stat {
  margin: 0 0 8px;
  font-size: 13px;
}
.archive-hint {
  margin: 0 0 12px;
  font-size: 12px;
  color: var(--el-text-color-secondary);
}
.archive-refund {
  display: flex;
  margin-bottom: 8px;
}
.archive-parlay-hint {
  margin: 0;
  font-size: 12px;
  color: var(--el-color-warning);
}
</style>
