<script setup lang="ts">
import { NButton, NCard, NInput, NModal, NSelect, NSpace, useMessage } from 'naive-ui'
import { computed, ref } from 'vue'
import { useRouterPush } from '@/hooks/common/router'
import { fetchAddExtraTime } from '@/service/api/game'

const props = defineProps<{
  show: boolean
  activityId: number
  teamOptions: { label: string, value: number }[]
}>()
const emit = defineEmits(['update:show', 'submit'])

const { routerPushByKey } = useRouterPush()
const message = useMessage()
const extraTimeGroups = ref<{
  GroupName: string
  TeamInfos: number[]
}[]>([{ GroupName: '', TeamInfos: [] }])

const selectedTeams = computed(() => extraTimeGroups.value.flatMap(g => g.TeamInfos))

function getFilteredOptions(currentGroupIndex: number) {
  const currentGroupTeams = extraTimeGroups.value[currentGroupIndex].TeamInfos
  return props.teamOptions.filter(option =>
    !selectedTeams.value.includes(option.value) || currentGroupTeams.includes(option.value),
  )
}

function addGroup() {
  extraTimeGroups.value.push({ GroupName: '', TeamInfos: [] })
}

function removeGroup(index: number) {
  extraTimeGroups.value.splice(index, 1)
}

async function handleSubmit() {
  const allSelectedTeams = new Set<number>()
  for (const group of extraTimeGroups.value) {
    if (!group.GroupName) {
      message.warning('请输入所有分组的名称')
      return
    }
    if (group.TeamInfos.length < 2) {
      message.warning(`分组 "${group.GroupName}" 至少需要选择两个队伍`)
      return
    }
    for (const teamId of group.TeamInfos) {
      if (allSelectedTeams.has(teamId)) {
        message.warning('同一个队伍不能出现在多个分组中')
        return
      }
      allSelectedTeams.add(teamId)
    }
  }

  const params: Api.Competition.AddExtraTimeParams = extraTimeGroups.value.map(group => ({
    ...group,
    ActivityID: props.activityId,
    TeamInfos: group.TeamInfos.map(teamId => ({
      TeamID: teamId,
      TeamName: props.teamOptions.find(opt => opt.value === teamId)?.label || '',
    })),
  }))

  const { data, error } = await fetchAddExtraTime(params)
  if (error) {
    message.error(error.message || '创建加时赛失败')
    return
  }

  message.success('加时赛已创建')
  emit('submit', data)
  emit('update:show', false)

  if (data) {
    routerPushByKey('user_cover', { query: { activityId: props.activityId, groupsId: data.data, RoundType: 1 } })
  }
}

function handleClose() {
  emit('update:show', false)
}
</script>

<template>
  <NModal :show="show" @update:show="handleClose">
    <NCard style="width: 600px" title="创建加时赛" :bordered="false" size="huge" role="dialog" aria-modal="true">
      <NSpace vertical>
        <div v-for="(group, index) in extraTimeGroups" :key="index" class="group-item">
          <NInput v-model:value="group.GroupName" placeholder="请输入分组名称" />
          <NSelect
            v-model:value="group.TeamInfos"
            multiple
            :options="getFilteredOptions(index)"
            placeholder="请选择队伍"
          />
          <NButton v-if="extraTimeGroups.length > 1" text @click="() => removeGroup(index)">
            删除
          </NButton>
        </div>
        <NButton type="dashed" block @click="addGroup">
          新增分组
        </NButton>
        <NButton type="primary" block @click="handleSubmit">
          确定
        </NButton>
      </NSpace>
    </NCard>
  </NModal>
</template>

<style scoped>
.group-item {
  display: flex;
  gap: 10px;
  align-items: center;
  margin-bottom: 10px;
}
</style>
