<template>
  <v-container fluid class="pa-6">
    <v-card elevation="0" border rounded="lg">
      <v-card-title class="d-flex align-center text-h6">
        重试队列
        <v-spacer />
        <v-select
          v-model="statusFilter"
          :items="statusOptions"
          item-title="label"
          item-value="value"
          label="状态筛选"
          variant="outlined"
          density="compact"
          hide-details
          style="max-width: 160px"
          clearable
          @update:model-value="page = 1; loadRetries()"
        />
      </v-card-title>

      <v-data-table-server
        :items="retries"
        :headers="headers"
        :items-length="total"
        :loading="loading"
        :page="page"
        :items-per-page="20"
        hover
        density="comfortable"
        @update:page="page = $event; loadRetries()"
      >
        <template #item.status="{ item }">
          <v-chip :color="retryColor(item.status)" size="x-small" variant="tonal" label border="sm">
            {{ retryLabel(item.status) }}
          </v-chip>
        </template>

        <template #item.operation="{ item }">
          <span class="font-weight-medium text-truncate d-inline-block" style="max-width: 240px">
            {{ retryOperationLabel(item) }}
          </span>
        </template>

        <template #item.server_name="{ item }">
          <span class="text-medium-emphasis">{{ item.server_name || '—' }}</span>
        </template>

        <template #item.retry_count="{ item }">
          <span class="text-medium-emphasis">{{ item.retry_count || 0 }} / {{ item.max_retries || 3 }}</span>
        </template>

        <template #item.next_retry_at="{ item }">
          <span class="text-caption text-medium-emphasis">{{ item.next_retry_at || '—' }}</span>
        </template>

        <template #item.created_at="{ item }">
          <span class="text-caption text-medium-emphasis">{{ item.created_at }}</span>
        </template>

        <template #item.actions="{ item }">
          <v-btn v-if="item.status === 'pending' || item.status === 'failed'" variant="text" size="x-small" color="primary" density="compact" @click="retryNow(item)">
            重试
          </v-btn>
          <v-btn variant="text" size="x-small" color="error" density="compact" @click="confirmDelete(item)">
            删除
          </v-btn>
        </template>
        <template #no-data>
          <div class="text-center text-medium-emphasis py-6">暂无数据</div>
        </template>
      </v-data-table-server>
    </v-card>

    <!-- Delete Confirm -->
    <v-dialog v-model="showDelete" max-width="400">
      <v-card border>
        <v-card-title>确认删除</v-card-title>
        <v-card-text>确定要删除此重试任务吗？</v-card-text>
        <v-card-actions>
          <v-spacer />
          <v-btn variant="text" @click="showDelete = false">取消</v-btn>
          <v-btn color="error" variant="flat" @click="doDelete">删除</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </v-container>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { http } from '@/api'
import { useSnackbar } from '@/composables/useSnackbar'
import type { PaginatedResponse, RetryItem } from '@/types/api'

const snackbar = useSnackbar()

// ── State ──
const loading = ref(false)
const retries = ref<RetryItem[]>([])
const total = ref(0)
const page = ref(1)
const statusFilter = ref<string | null>(null)

const showDelete = ref(false)
const deletingId = ref<number | null>(null)

const statusOptions = [
  { label: '待重试', value: 'pending' },
  { label: '重试中', value: 'retrying' },
  { label: '成功', value: 'success' },
  { label: '失败', value: 'failed' },
]

const headers = [
  { title: '状态', key: 'status', width: 100 },
  { title: '任务', key: 'operation' },
  { title: '服务器', key: 'server_name' },
  { title: '次数', key: 'retry_count', width: 100 },
  { title: '下次重试', key: 'next_retry_at', width: 140 },
  { title: '创建时间', key: 'created_at', width: 160 },
  { title: '', key: 'actions', width: 120, align: 'end' as const, sortable: false },
]

// ── Data loading ──
async function loadRetries() {
  loading.value = true
  try {
    const res = await http.getList<RetryItem>('/retries/', { limit: 200 })
    let all = res.items || []
    if (statusFilter.value) all = all.filter((r) => r.status === statusFilter.value)
    total.value = all.length
    const start = (page.value - 1) * 20
    retries.value = all.slice(start, start + 20)
  } catch (e: unknown) {
    retries.value = []
    total.value = 0
    snackbar(e instanceof Error ? e.message : '加载重试队列失败', 'error')
  }
  finally { loading.value = false }
}

// ── Actions ──
async function retryNow(item: RetryItem) {
  try {
    await http.post(`/retries/${item.id}/retry`)
    loadRetries()
    snackbar('重试已触发')
  } catch (e: any) { snackbar(e.message || '操作失败', 'error') }
}

function confirmDelete(item: RetryItem) {
  deletingId.value = item.id
  showDelete.value = true
}

async function doDelete() {
  if (!deletingId.value) return
  try {
    await http.delete(`/retries/${deletingId.value}`)
    showDelete.value = false
    loadRetries()
    snackbar('已删除')
  } catch (e: any) { snackbar(e.message || '删除失败', 'error') }
}

// ── Helpers ──
function retryColor(s: string) {
  if (s === 'success') return 'success'
  if (s === 'failed') return 'error'
  if (s === 'retrying') return 'warning'
  return 'info'
}
function retryLabel(s: string) {
  if (s === 'pending') return '待重试'
  if (s === 'retrying') return '重试中'
  if (s === 'success') return '成功'
  if (s === 'failed') return '失败'
  return s
}

function retryOperationLabel(item: RetryItem): string {
  if (item.source_path && item.target_path) {
    return `${item.source_path} → ${item.target_path}`
  }
  return item.source_path || item.target_path || '文件推送'
}


onMounted(() => loadRetries())
</script>
