<script setup lang="ts">
import { computed, onMounted, reactive, shallowRef } from 'vue'
import { ElMessage } from 'element-plus'
import { Edit, Plus, UserFilled } from '@element-plus/icons-vue'
import { addClassMembers, createClass, fetchClasses, fetchUsers, updateClass } from '@/api/admin'
import type { SchoolClass, User } from '@/types/api'

const loading = shallowRef(false)
const dialogVisible = shallowRef(false)
const memberVisible = shallowRef(false)
const dialogMode = shallowRef<'create' | 'edit'>('create')
const classes = shallowRef<SchoolClass[]>([])
const users = shallowRef<User[]>([])
const selectedClass = shallowRef<SchoolClass | null>(null)
const form = reactive({
  name: '',
  description: '',
  is_active: true,
})
const memberForm = reactive({
  user_ids: [] as number[],
  role: 'student',
})
const activeUsers = computed(() => users.value.filter((item) => item.is_active))
const dialogTitle = computed(() => (dialogMode.value === 'create' ? '新建班级' : '编辑班级'))

async function loadClasses() {
  loading.value = true
  try {
    const response = await fetchClasses()
    classes.value = response.data.items
  } finally {
    loading.value = false
  }
}

async function loadUsers() {
  const response = await fetchUsers({ per_page: 100 })
  users.value = response.data.items
}

function resetForm() {
  form.name = ''
  form.description = ''
  form.is_active = true
}

function openCreateDialog() {
  dialogMode.value = 'create'
  selectedClass.value = null
  resetForm()
  dialogVisible.value = true
}

function openEditDialog(row: SchoolClass) {
  dialogMode.value = 'edit'
  selectedClass.value = row
  form.name = row.name
  form.description = row.description ?? ''
  form.is_active = row.is_active
  dialogVisible.value = true
}

async function submitClass() {
  if (dialogMode.value === 'create') {
    await createClass({ name: form.name, description: form.description })
    ElMessage.success('班级已创建')
  } else if (selectedClass.value) {
    await updateClass(selectedClass.value.id, form)
    ElMessage.success('班级已更新')
  }
  dialogVisible.value = false
  resetForm()
  await loadClasses()
}

function openMemberDialog(row: SchoolClass) {
  selectedClass.value = row
  memberForm.user_ids = []
  memberForm.role = 'student'
  memberVisible.value = true
}

async function submitMember() {
  if (!selectedClass.value || memberForm.user_ids.length === 0) return
  await addClassMembers(selectedClass.value.id, {
    user_ids: memberForm.user_ids,
    role: memberForm.role,
  })
  ElMessage.success('成员已加入班级')
  memberVisible.value = false
  await loadClasses()
}

onMounted(() => {
  void loadClasses()
  void loadUsers()
})
</script>

<template>
  <section class="panel p-5">
    <div class="toolbar mb-4">
      <div class="flex-1">
        <h1 class="page-title">班级管理</h1>
        <p class="muted text-sm mt-1">创建班级，使用班级码或后台分配成员。</p>
      </div>
      <ElButton :icon="Plus" type="primary" @click="openCreateDialog">新建班级</ElButton>
    </div>

    <ElTable v-loading="loading" :data="classes" row-key="id">
      <ElTableColumn prop="name" label="班级名称" min-width="180" />
      <ElTableColumn prop="join_code" label="班级码" width="140">
        <template #default="{ row }">
          <ElTag type="success">{{ row.join_code }}</ElTag>
        </template>
      </ElTableColumn>
      <ElTableColumn prop="members_count" label="成员数" width="100" />
      <ElTableColumn prop="description" label="说明" min-width="220" show-overflow-tooltip />
      <ElTableColumn prop="is_active" label="状态" width="100">
        <template #default="{ row }">
          <ElTag :type="row.is_active ? 'success' : 'info'">{{ row.is_active ? '启用' : '停用' }}</ElTag>
        </template>
      </ElTableColumn>
      <ElTableColumn label="操作" width="230" fixed="right">
        <template #default="{ row }">
          <ElButton :icon="Edit" size="small" @click="openEditDialog(row)">编辑</ElButton>
          <ElButton :icon="UserFilled" size="small" @click="openMemberDialog(row)">分配成员</ElButton>
        </template>
      </ElTableColumn>
    </ElTable>
  </section>

  <ElDialog v-model="dialogVisible" :title="dialogTitle" width="420px">
    <ElForm :model="form" label-position="top">
      <ElFormItem label="名称">
        <ElInput v-model="form.name" />
      </ElFormItem>
      <ElFormItem label="说明">
        <ElInput v-model="form.description" type="textarea" />
      </ElFormItem>
      <ElFormItem v-if="dialogMode === 'edit'" label="状态">
        <ElSwitch v-model="form.is_active" active-text="启用" inactive-text="停用" />
      </ElFormItem>
    </ElForm>
    <template #footer>
      <ElButton @click="dialogVisible = false">取消</ElButton>
      <ElButton type="primary" @click="submitClass">保存</ElButton>
    </template>
  </ElDialog>

  <ElDialog v-model="memberVisible" title="分配成员" width="420px">
    <ElForm :model="memberForm" label-position="top">
      <ElFormItem label="用户">
        <ElSelect v-model="memberForm.user_ids" class="w-full" filterable multiple collapse-tags collapse-tags-tooltip placeholder="可一次选择多个用户">
          <ElOption
            v-for="item in activeUsers"
            :key="item.id"
            :label="`${item.name} / ${item.email}`"
            :value="item.id"
          />
        </ElSelect>
      </ElFormItem>
      <ElFormItem label="班级角色">
        <ElSegmented v-model="memberForm.role" :options="[
          { label: '学生', value: 'student' },
          { label: '助教', value: 'assistant' },
        ]" />
      </ElFormItem>
    </ElForm>
    <template #footer>
      <ElButton @click="memberVisible = false">取消</ElButton>
      <ElButton type="primary" @click="submitMember">保存</ElButton>
    </template>
  </ElDialog>
</template>
