<script setup lang="ts">
import { NButton, NGi, NGrid, NSpace } from 'naive-ui'
import { computed, ref } from 'vue'
import { useAppStore } from '@/store/modules/app'
import CompetitionAddModal from '../competition-add/index.vue'
import CompetitionCard from './modules/competition-card.vue'
import { type CompetitionItem, competitionList } from './modules/data'

const appStore = useAppStore()
const gap = computed(() => (appStore.isMobile ? 12 : 26))

const competitionListRef = ref(competitionList)

const showAddModal = ref(false)

function handleAdd() {
  showAddModal.value = true
}

function handleCopy(item: CompetitionItem) {
  // TODO: 实现复制逻辑
  window.$message?.success(`已复制活动：${item.title}`)
}

function handleDelete(item: CompetitionItem) {
  const d = window.$dialog?.warning({
    title: '确认删除',
    content: `确定删除活动：${item.title}吗？`,
    positiveText: '确认',
    negativeText: '取消',
    onPositiveClick: async () => {
      if (d) {
        d.loading = true
      }
      // 模拟接口请求延迟 2秒
      await new Promise(resolve => setTimeout(resolve, 2000))

      try {
        // 模拟 50% 概率失败
        if (Math.random() < 0.5) {
          throw new Error('模拟服务器异常，删除失败')
        }

        // 成功逻辑
        const index = competitionListRef.value.findIndex(i => i.id === item.id)
        if (index > -1) {
          competitionListRef.value.splice(index, 1)
          window.$message?.success(`已删除活动：${item.title}`)
        }
        return true // 返回 true 关闭弹窗
      }
      catch (error: any) {
        window.$message?.error(error.message)
        return false // 返回 false 阻止关闭弹窗
      }
      finally {
        if (d) {
          d.loading = false
        }
      }
    },
  })
}
</script>

<template>
  <NSpace vertical :size="24">
    <!-- 顶部 Header 区域 -->
    <div class="flex flex-col justify-between gap-4 sm:flex-row sm:items-center">
      <div>
        <h2 class="m-0 text-xl text-gray-800 font-bold dark:text-white">
          比赛列表
        </h2>
        <p class="mt-1 text-sm text-gray-500">
          管理并配置所有阅读大比拼活动
        </p>
      </div>

      <NButton type="primary" size="large" class="px-6 font-medium" @click="handleAdd">
        <template #icon>
          <icon-ic-outline-add-to-photos class="text-icon" />
        </template>
        新增比赛活动
      </NButton>
    </div>

    <!-- 卡片列表区域 -->
    <!-- 响应式布局：手机1列，平板2列，中屏3列，大屏4列 -->
    <NGrid :x-gap="gap" :y-gap="gap" responsive="screen" item-responsive>
      <NGi v-for="item in competitionListRef" :key="item.id" span="24 s:12 m:8 l:6">
        <CompetitionCard :item="item" @copy="handleCopy" @delete="handleDelete" />
      </NGi>
    </NGrid>

    <CompetitionAddModal v-model:show="showAddModal" />
  </NSpace>
</template>

<style scoped>
/* 针对不同屏幕微调间距 */
</style>
