<script setup lang="ts">
import { NButton, NGrid, NGridItem, NInput } from 'naive-ui'
import { useExcelExport, useExcelImport, useGroupManagement } from './useGroupManagement'

const props = defineProps<{
  config?: {
    groupCount: number
    teamCount: number
  }
}>()

const { groups, validate, reset } = useGroupManagement(props)
const { downloadTemplate } = useExcelExport(props, groups)
const { fileInputRef, handleImportClick, handleFileChange } = useExcelImport(props, groups)

defineExpose({ validate, reset })
</script>

<template>
  <div class="h-full">
    <!-- 头部区域 -->
    <div class="mb-8 flex items-end justify-between">
      <div>
        <h2 class="mb-2 text-3xl text-gray-800 font-bold">
          参赛名单录入
        </h2>
        <p class="text-gray-400">
          系统已根据您的设置生成了 {{ groups.length }} 个分组。您可以手动填写或批量导入。
        </p>
      </div>
      <div class="flex gap-3">
        <NButton secondary type="primary" @click="downloadTemplate">
          <template #icon>
            <icon-ic-baseline-download class="text-icon" />
          </template>
          下载导入模板
        </NButton>
        <NButton type="primary" color="#1a202c" @click="handleImportClick">
          <template #icon>
            <icon-ic-baseline-upload-file class="text-icon" />
          </template>
          Excel 导入名单
        </NButton>
        <!-- 隐藏的文件上传 Input -->
        <input ref="fileInputRef" type="file" class="hidden" accept=".xlsx, .xls" @change="handleFileChange">
      </div>
    </div>

    <!-- 分组卡片列表 -->
    <NGrid :x-gap="24" :y-gap="24" cols="1 m:2 l:3" responsive="screen">
      <NGridItem v-for="(group, index) in groups" :key="index">
        <div
          class="h-full border border-gray-100 rounded-2xl bg-[#F8FAFC] p-6 transition-all hover:bg-white hover:shadow-lg"
        >
          <div class="mb-6 flex items-center justify-between gap-4">
            <span class="shrink-0 text-lg text-gray-800 font-bold">{{ group.name }}</span>
          </div>

          <NGrid :x-gap="16" :y-gap="16" :cols="2">
            <NGridItem v-for="(team, tIndex) in group.teams" :key="tIndex">
              <div class="mb-1 text-xs text-gray-400 font-bold">
                <!-- 显示分组序号，从1到teamCount -->
                TEAM {{ tIndex + 1 }}
                <!-- // 显示分组序号，从1到groups.length*teamCount -->
                <!-- TEAM {{ (index + 1) * (props.config?.teamCount ?? 0) - (props.config?.teamCount ?? 0) + tIndex + 1 }} -->
              </div>
              <NInput v-model:value="team.name" placeholder="输入队伍名称" class="rounded-lg !bg-white" />
            </NGridItem>
          </NGrid>
        </div>
      </NGridItem>
    </NGrid>
  </div>
</template>
