<script setup lang="ts">
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useGroupStore } from '@/stores/group'
import { createGroup } from '@/api/groups'
import pb from '@/api/pocketbase'

const props = defineProps<{
  modelValue: boolean
}>()

const emit = defineEmits<{
  'update:modelValue': [value: boolean]
}>()

const router = useRouter()
const groupStore = useGroupStore()

const visible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

const form = ref({
  name: '',
  description: '',
  maxMembers: 20
})
const loading = ref(false)

async function handleSubmit() {
  if (!form.value.name.trim()) {
    ElMessage.warning('请输入群组名称')
    return
  }

  // 检查群组名是否重复
  loading.value = true
  try {
    const existing = await pb.collection('groups').getList(1, 1, {
      filter: `name="${form.value.name.trim()}"`
    })
    if (existing.items.length > 0) {
      ElMessage.warning('该群组名称已存在，请换一个')
      loading.value = false
      return
    }
  } catch { /* ignore */ }

  try {
    const group = await createGroup({
      name: form.value.name.trim(),
      description: form.value.description.trim(),
      maxMembers: form.value.maxMembers
    })
    await groupStore.loadGroups()
    visible.value = false
    form.value = { name: '', description: '', maxMembers: 20 }
    ElMessage.success('群组创建成功')
    if (group?.id) {
      router.push({ name: 'GroupView', params: { id: group.id } })
    }
  } catch (error: any) {
    ElMessage.error(error.message || '创建群组失败')
  } finally {
    loading.value = false
  }
}
</script>

<template>
  <el-dialog v-model="visible" title="创建群组" width="440px">
    <div class="create-form">
      <div class="form-field">
        <label>群组名称 <span class="required">*</span></label>
        <el-input v-model="form.name" placeholder="给群组起个名字" maxlength="50" show-word-limit />
      </div>
      <div class="form-field">
        <label>群组描述</label>
        <el-input v-model="form.description" type="textarea" :rows="3" placeholder="简单介绍这个群组" maxlength="500" show-word-limit />
      </div>
      <div class="form-field">
        <label>最大成员数</label>
        <el-input-number v-model="form.maxMembers" :min="2" :max="100" />
      </div>
    </div>
    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" :loading="loading" @click="handleSubmit">创建</el-button>
    </template>
  </el-dialog>
</template>

<style scoped>
.create-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-field {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-field label {
  font-size: 14px;
  font-weight: 500;
  color: var(--gg-text);
}

.required {
  color: var(--gg-danger);
}
</style>
