<script setup lang="ts">
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { NAlert, NDatePicker, NForm, NInput, NInputNumber, NSelect } from 'naive-ui'
import { onBeforeUnmount, ref, shallowRef, useTemplateRef } from 'vue'
import OssImageUpload from '@/components/common/oss-image-upload/index.vue'
import { useBasicInfo } from './useBasicInfo'
import '@wangeditor/editor/dist/css/style.css'

const props = defineProps<{
  modelValue: {
    name: string
    subTitle?: string
    startTime: string | null
    endTime: string | null
    groupCount: number
    teamCount: number
    poster: string
    roomId: number | null
    activityContent: string
    extraTimeContent: string
    [key: string]: any
  }
  /** 房间列表 */
  roomListOptions: { label: string, value: number }[]
}>()

const emit = defineEmits(['update:modelValue'])

const formRef = useTemplateRef('formRef')

const { formData, updateCount, validate, reset } = useBasicInfo(props, emit)

// Editor Logic
const editorRef = shallowRef()
const mode = 'default'
const toolbarConfig = {
  excludeKeys: ['group-video', 'insertVideo', 'uploadVideo'],
}
const editorConfig = { placeholder: '请输入具体的比赛参与规则及计分标准...' }
const activeTab = ref('normal') // normal or extra

function handleCreated(editor: any) {
  editorRef.value = editor
}

onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null)
    return
  editor.destroy()
})

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

<template>
  <div class="h-full flex gap-12 overflow-hidden">
    <!-- 左侧表单区域 -->
    <div class="no-scrollbar h-full flex-1 overflow-y-auto">
      <div class="mb-6">
        <h2 class="mb-2 text-3xl text-gray-800 font-bold">
          第一步： 基础定义
        </h2>
        <p class="text-16px text-gray-400 font-bold">
          请确认比赛名称与参与规模。这将作为系统自动生成分组与终端连接数的依据。
        </p>
      </div>

      <NForm ref="formRef" label-placement="top" :show-feedback="false">
        <div class="mb-6">
          <div class="mb-3 text-sm text-[#8DA5C3] font-bold">
            比赛项目名称
            <span class="text-red-500">*</span>
          </div>
          <NInput
            v-model:value="formData.name" placeholder="例如：2026年度阅读之星-辞海遨游总决赛"
            class="h-[3.4rem] rounded-2xl border-none text-xl leading-[3.4rem] shadow-[0_2px_10px_rgba(0,0,0,0.02)] !bg-[#FCFCFC]"
          />
        </div>

        <div class="mb-6">
          <div class="mb-3 text-sm text-[#8DA5C3] font-bold">
            活动副标题
            <span class="ml-2 text-gray-400 font-normal">(选填)</span>
          </div>
          <NInput
            v-model:value="formData.subTitle" placeholder="请输入活动口号或副标题"
            class="h-[3rem] rounded-2xl border-none text-xl leading-[3rem] shadow-[0_2px_10px_rgba(0,0,0,0.02)] !bg-[#FCFCFC]"
          />
        </div>

        <div class="mb-6">
          <div class="mb-3 text-sm text-[#8DA5C3] font-bold">
            关联场地AP
            <span class="text-red-500">*</span>
          </div>
          <NSelect
            v-model:value="formData.roomId" placeholder="选择关联场地AP"
            class="rounded-2xl border-none shadow-[0_2px_10px_rgba(0,0,0,0.02)] !bg-[#FCFCFC]"
            :options="roomListOptions"
            size="large"
            :theme-overrides="{
              peers: {
                InternalSelection: {
                  heightLarge: '3rem',
                  color: '#FCFCFC',
                  borderRadius: '1rem',
                  fontSizeLarge: '1.2rem',
                  borderHover: 'none',
                  borderFocus: 'none',
                  boxShadowHover: 'none',
                  boxShadowFocus: 'none',
                  boxShadowActive: 'none',
                },
              },
            }"
          />
        </div>

        <div class="grid grid-cols-2 mb-10 gap-8">
          <div>
            <div class="mb-3 text-sm text-[#8DA5C3] font-bold">
              开始时间
              <span class="text-red-500">*</span>
            </div>
            <NDatePicker
              v-model:formatted-value="formData.startTime" type="datetime" clearable class="w-full"
              value-format="yyyy-MM-dd'T'HH:mm:ss"
              placeholder="选择开始时间" :theme-overrides="{
                peers: {
                  Input: {
                    borderRadius: '1rem',
                    color: '#FCFCFC',
                    heightLarge: '3rem',
                    fontSizeLarge: '1.2rem',
                    textColor: '#1f2937',
                    borderHover: 'none',
                    borderFocus: 'none',
                  },
                },
              }" size="large"
            />
          </div>
          <div>
            <div class="mb-3 text-sm text-[#8DA5C3] font-bold">
              结束时间
              <span class="text-red-500">*</span>
            </div>
            <NDatePicker
              v-model:formatted-value="formData.endTime" type="datetime" clearable class="w-full" placeholder="选择结束时间"
              value-format="yyyy-MM-dd'T'HH:mm:ss"
              :theme-overrides="{
                peers: {
                  Input: {
                    borderRadius: '1rem',
                    color: '#FCFCFC',
                    heightLarge: '3rem',
                    fontSizeLarge: '1.25rem',
                    textColor: '#1f2937',
                    borderHover: 'none',
                    borderFocus: 'none',
                  },
                },
              }" size="large"
            />
          </div>
        </div>

        <div class="grid grid-cols-2 gap-8">
          <!-- 参赛小组数量卡片 -->
          <div class="rounded-3xl bg-[#F5F8FF] p-8">
            <div class="mb-6 text-sm text-[#3B82F6] font-bold tracking-wide uppercase">
              参赛小组总数 (GROUPS)
            </div>
            <div class="mb-6 flex items-center justify-between">
              <button
                class="h-14 w-14 flex items-center justify-center rounded-full bg-white text-3xl text-[#3B82F6] shadow-md transition-transform active:scale-95 hover:bg-gray-50"
                @click="updateCount('group', -1)"
              >
                <div class="mb-1 font-bold">
                  -
                </div>
              </button>
              <div class="w-32">
                <NInputNumber
                  v-model:value="formData.groupCount" :min="1" :max="999" :show-button="false"
                  class="text-center" :theme-overrides="{
                    peers: {
                      Input: {
                        textColor: '#1f2937',
                        fontSizeMedium: '3rem',
                        heightMedium: '3rem',
                        color: 'transparent',
                        caretColor: '#3B82F6',
                      },
                    },
                  }"
                />
              </div>
              <button
                class="h-14 w-14 flex items-center justify-center rounded-full bg-white text-3xl text-[#3B82F6] shadow-md transition-transform active:scale-95 hover:bg-gray-50"
                @click="updateCount('group', 1)"
              >
                <div class="mb-1 font-bold">
                  +
                </div>
              </button>
            </div>
            <div class="text-center text-sm text-[#3B82F6]/60 font-medium italic">
              系统将预设 {{ formData.groupCount }} 个队伍
            </div>
          </div>

          <!-- 每组队伍数量卡片 -->
          <div class="rounded-3xl bg-[#F5F8FF] p-8">
            <div class="mb-6 text-sm text-[#3B82F6] font-bold tracking-wide uppercase">
              单组包含队伍 (TEAMS)
            </div>
            <div class="mb-6 flex items-center justify-between">
              <button
                class="h-14 w-14 flex items-center justify-center rounded-full bg-white text-3xl text-[#3B82F6] shadow-md transition-transform active:scale-95 hover:bg-gray-50"
                @click="updateCount('team', -1)"
              >
                <div class="mb-1 font-bold">
                  -
                </div>
              </button>
              <div class="w-32">
                <NInputNumber
                  v-model:value="formData.teamCount" :min="1" :max="999" :show-button="false"
                  class="text-center" :theme-overrides="{
                    peers: {
                      Input: {
                        textColor: '#1f2937',
                        fontSizeMedium: '3rem',
                        heightMedium: '4rem',
                        color: 'transparent',
                        caretColor: '#3B82F6',
                      },
                    },
                  }"
                />
              </div>
              <button
                class="h-14 w-14 flex items-center justify-center rounded-full bg-white text-3xl text-[#3B82F6] shadow-md transition-transform active:scale-95 hover:bg-gray-50"
                @click="updateCount('team', 1)"
              >
                <div class="mb-1 font-bold">
                  +
                </div>
              </button>
            </div>
            <div class="text-center text-sm text-[#3B82F6]/60 font-medium italic">
              每组将有 {{ formData.teamCount }} 支队伍同时进行比赛
            </div>
          </div>
        </div>
      </NForm>
    </div>

    <!-- 右侧区域：规则编辑与海报 -->
    <div class="no-scrollbar h-full flex flex-col flex-1 gap-10 overflow-y-auto pr-2">
      <!-- 活动规则 -->
      <div>
        <div class="mb-3 flex items-center justify-between">
          <div class="text-sm text-[#8DA5C3] font-bold">
            活动规则配置
            <span class="text-red-500">*</span>
          </div>
          <!-- 切换 Tab -->
          <div class="flex rounded-lg bg-gray-100 p-1">
            <button
              class="rounded-md px-4 py-1.5 text-sm font-medium transition-all"
              :class="activeTab === 'normal' ? 'bg-[#3B82F6] text-white shadow-sm' : 'text-gray-500 hover:text-gray-700'"
              @click="activeTab = 'normal'"
            >
              普通赛事
            </button>
            <button
              class="rounded-md px-4 py-1.5 text-sm font-medium transition-all"
              :class="activeTab === 'extra' ? 'bg-[#3B82F6] text-white shadow-sm' : 'text-gray-500 hover:text-gray-700'"
              @click="activeTab = 'extra'"
            >
              加时赛
            </button>
          </div>
        </div>

        <div class="overflow-hidden border border-gray-100 rounded-3xl bg-white shadow-sm">
          <Toolbar
            style="border-bottom: 1px solid #eee"
            :editor="editorRef"
            :default-config="toolbarConfig"
            :mode="mode"
          />
          <div class="relative h-[400px]">
            <div v-show="activeTab === 'normal'" class="h-full">
              <Editor
                v-model="formData.activityContent"
                style="height: 100%; overflow-y: hidden;"
                :default-config="{ ...editorConfig, placeholder: '请输入普通赛事的参与规则及计分标准...' }"
                :mode="mode"
                @on-created="handleCreated"
              />
            </div>
            <div v-show="activeTab === 'extra'" class="h-full">
              <Editor
                v-model="formData.extraTimeContent"
                style="height: 100%; overflow-y: hidden;"
                :default-config="{ ...editorConfig, placeholder: '请输入加时赛的参与规则及计分标准...' }"
                :mode="mode"
                @on-created="handleCreated"
              />
            </div>
          </div>
        </div>
      </div>

      <!-- 海报上传 -->
      <div class="w-full">
        <div class="mb-3 w-full text-sm text-[#8DA5C3] font-bold">
          活动海报
          <NAlert type="info" class="mt-2 text-xs text-[#616263] font-normal" :bordered="false">
            <span class="text-xs font-normal">
              建议上传 16:9 或 4:3 比例的图片，以获得最佳的全屏显示效果。
            </span>
          </NAlert>
        </div>
        <OssImageUpload
          v-model="formData.poster"
          hint="支持 JPG/PNG 格式"
          accept="image/*"
          :max-size="5120"
        />
      </div>
    </div>
  </div>
</template>

<style scoped>
:deep(.n-input-number .n-input__input-el) {
  text-align: center;
  font-family: inherit;
  font-weight: 700;
}

:deep(.n-upload-trigger) {
  width: 100%;
}

.no-scrollbar::-webkit-scrollbar {
  display: none;
}
.no-scrollbar {
  -ms-overflow-style: none;
  scrollbar-width: none;
}
</style>
