<script setup lang="ts">
import { NButton, NGi, NGrid, NSpace } from 'naive-ui'
import { computed, onMounted, ref } from 'vue'
import { useRouterPush } from '@/hooks/common/router'
import { fetchCopyActivity, fetchDeleteActivity, fetchGetActivityList } from '@/service/api/competition'
import { endActivity } from '@/service/api/result'
import { useAppStore } from '@/store/modules/app'
import CompetitionAddModal from '../competition-add/index.vue'

import CompetitionCard from './modules/competition-card.vue'

const { routerPushByKey } = useRouterPush()

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

const competitionListRef = ref<Api.Competition.CompetitionItem[]>([])

const showAddModal = ref(false)

function handleAdd() {
  showAddModal.value = true
}

async function handleCopy(item: Api.Competition.CompetitionItem) {
  // TODO: 实现复制逻辑
  try {
    const { error } = await fetchCopyActivity(item.Id)
    if (error) {
      window.$message?.error(error.message || '复制失败')
      return
    }
  }
  catch (e) {
    console.error(e)
    window.$message?.error('复制失败')
    return
  }
  window.$message?.success(`已复制活动：${item.Name}`)
  // 刷新列表
  fetchActivityList()
}

function handleDelete(item: Api.Competition.CompetitionItem) {
  const d = window.$dialog?.warning({
    title: '确认删除',
    content: `确定删除活动：${item.Name}吗？`,
    positiveText: '确认',
    negativeText: '取消',
    onPositiveClick: async () => {
      if (d) {
        d.loading = true
      }

      try {
        const { error } = await fetchDeleteActivity(item.Id)
        if (error) {
          window.$message?.error(error.message || '删除失败')
          return false
        }

        // 成功逻辑
        window.$message?.success(`已删除活动：${item.Name}`)
        // 刷新列表
        fetchActivityList()
        return true
      }
      catch (error: any) {
        window.$message?.error(error.message)
        return false
      }
      finally {
        if (d) {
          d.loading = false
        }
      }
    },
  })
}

/** 获取活动列表 */
async function fetchActivityList() {
  try {
    const { response, error } = await fetchGetActivityList()
    if (!error) {
      competitionListRef.value = response?.data?.data || []
    }
  }
  catch (e) {
    console.error(e)
  }
}

function toDetail(item: Api.Competition.CompetitionItem) {
  routerPushByKey('competition_competition-detail', { query: { Id: item.Id.toString() } })
}

async function handleCloseActivity(item: Api.Competition.CompetitionItem) {
  const d = window.$dialog?.warning({
    title: '确认结束',
    content: `确定结束活动：${item.Name}吗？结束活动后将生成排行榜数据。`,
    positiveText: '确认结束',
    negativeText: '取消',
    onPositiveClick: async () => {
      if (d) {
        d.loading = true
      }
      try {
        const { error } = await endActivity(item.Id)
        if (error) {
          window.$message?.error(error.message || '结束活动失败')
          return false
        }
        window.$message?.success(`已结束活动：${item.Name}`)
        fetchActivityList()
        return true
      }
      catch (e: any) {
        window.$message?.error(e.message || '操作失败')
        return false
      }
      finally {
        if (d) {
          d.loading = false
        }
      }
    },
  })
}

onMounted(() => fetchActivityList())
</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" @click="toDetail(item)">
        <CompetitionCard :item="item" @copy="handleCopy" @delete="handleDelete" @close="handleCloseActivity" />
      </NGi>
    </NGrid>

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

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