<template>
  <div class="create-group-container">
    <h2>创建新的兴趣小组</h2>
    <form @submit.prevent="handleCreateGroup" class="create-group-form">
      <div class="form-group">
        <label for="group-name">小组名称:</label>
        <input type="text" id="group-name" v-model="groupData.name" required maxlength="100" />
        <small v-if="errors.name" class="error-text">{{ errors.name.join(', ') }}</small>
      </div>

      <div class="form-group">
        <label for="group-description">小组描述 (可选):</label>
        <textarea id="group-description" v-model="groupData.description"></textarea>
        <small v-if="errors.description" class="error-text">{{ errors.description.join(', ') }}</small>
      </div>

      <div class="form-group">
        <label for="group-cover">小组封面 (可选):</label>
        <input type="file" id="group-cover" @change="handleCoverImageChange" accept="image/*" />
        <div v-if="coverPreviewUrl" class="cover-preview-container">
          <p>封面预览:</p>
          <img :src="coverPreviewUrl" alt="Cover Preview" class="cover-preview-small">
        </div>
        <small v-if="errors.cover_image" class="error-text">{{ errors.cover_image.join(', ') }}</small>
      </div>

      <div class="form-group">
        <label>选择兴趣标签 (可选):</label>
        <div v-if="availableTags.length > 0" class="tags-selection">
          <div v-for="tag in availableTags" :key="tag.id" class="tag-item">
            <input type="checkbox" :id="'tag-create-' + tag.id" :value="tag.id" v-model="groupData.tags" />
            <label :for="'tag-create-' + tag.id">{{ tag.name }}</label>
          </div>
        </div>
        <p v-else-if="isLoadingTags" class="loading-message-small">正在加载可选标签...</p>
        <p v-else>暂无可选标签。</p>
        <small v-if="errors.tags" class="error-text">{{ errors.tags.join(', ') }}</small>
      </div>
      
      <!-- (可选) 如果有小组类型选择
      <div class="form-group">
        <label for="group-type">小组类型:</label>
        <select id="group-type" v-model="groupData.group_type">
          <option value="public">公开小组</option>
          <option value="private">私密小组</option>
        </select>
      </div>
      -->

      <div class="form-actions">
        <button type="submit" :disabled="isSubmitting">
          {{ isSubmitting ? '创建中...' : '创建小组' }}
        </button>
        <router-link :to="{ name: 'GroupList' }" class="cancel-button">取消</router-link>
      </div>
      <p v-if="submitError" class="error-message">{{ submitError }}</p>
      <p v-if="successMessage" class="success-message">{{ successMessage }}</p>
    </form>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue';
import apiClient from '../services/api';
import { useRouter } from 'vue-router';
import { useAuthStore } from '../store/auth';

const groupData = reactive({
  name: '',
  description: '',
  cover_image: null, // File object
  tags: [],          // Array of selected tag IDs
  // group_type: 'public', // 如果有小组类型
});
const coverPreviewUrl = ref(null);

const availableTags = ref([]);
const isLoadingTags = ref(false);

const isSubmitting = ref(false);
const submitError = ref(''); // 用于提交时的整体错误
const errors = ref({}); // 用于存储字段特定的错误
const successMessage = ref('');

const router = useRouter();
const authStore = useAuthStore(); // 用于确保用户已登录 (通过路由守卫)

const fetchAvailableTags = async () => {
  isLoadingTags.value = true;
  try {
    const response = await apiClient.get('accounts/tags/'); // API端点获取标签列表
    availableTags.value = response.data.results || response.data;
  } catch (error) {
    console.error('获取兴趣标签失败:', error);
    submitError.value = '无法加载可选兴趣标签，但您仍可创建小组。';
  } finally {
    isLoadingTags.value = false;
  }
};

const handleCoverImageChange = (event) => {
  const file = event.target.files[0];
  if (file) {
    groupData.cover_image = file;
    const reader = new FileReader();
    reader.onload = (e) => {
      coverPreviewUrl.value = e.target.result;
    };
    reader.readAsDataURL(file);
  } else {
    groupData.cover_image = null;
    coverPreviewUrl.value = null;
  }
};

const handleCreateGroup = async () => {
  isSubmitting.value = true;
  submitError.value = '';
  errors.value = {};
  successMessage.value = '';

  const submissionData = new FormData();
  submissionData.append('name', groupData.name);
  if (groupData.description) submissionData.append('description', groupData.description);
  if (groupData.cover_image) submissionData.append('cover_image', groupData.cover_image);
  
  if (groupData.tags && groupData.tags.length > 0) {
    groupData.tags.forEach(tagId => {
      submissionData.append('tags', String(tagId));
    });
  }
  // if (groupData.group_type) submissionData.append('group_type', groupData.group_type);

  try {
    // 后端 GroupViewSet 的 perform_create 会自动将 request.user 设为 creator
    const response = await apiClient.post('groups/', submissionData); // POST 到 /api/v1/groups/
    
    console.log('小组创建成功:', response.data);
    successMessage.value = `小组 "${response.data.name}" 创建成功！即将跳转到小组列表...`;
    
    // 清空表单
    Object.keys(groupData).forEach(key => {
        if (key === 'tags') groupData[key] = [];
        else if (key === 'cover_image') groupData[key] = null;
        // else if (key === 'group_type') groupData[key] = 'public';
        else groupData[key] = '';
    });
    coverPreviewUrl.value = null;

    setTimeout(() => {
      router.push({ name: 'GroupList' }); // 或者跳转到新创建的小组详情页: router.push({ name: 'GroupDetail', params: { id: response.data.id } });
    }, 2000);

  } catch (error) {
    console.error('创建小组失败:', error.response ? error.response.data : error.message);
    if (error.response && error.response.data) {
      if (typeof error.response.data === 'object' && !error.response.data.detail) {
        // 将字段错误放到 errors ref 中
        errors.value = error.response.data;
        submitError.value = '请更正表单中的错误。';
      } else {
        submitError.value = error.response.data.detail || '创建小组失败，请稍后重试。';
      }
    } else {
      submitError.value = '创建小组时发生网络错误或服务器无响应。';
    }
  } finally {
    isSubmitting.value = false;
  }
};

onMounted(() => {
  fetchAvailableTags(); // 获取可选标签
});
</script>

<style scoped>
.create-group-container {
  max-width: 700px;
  margin: 30px auto;
  padding: 30px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.1);
}
.create-group-container h2 {
    text-align: center;
    margin-bottom: 25px;
    color: #333;
}
.create-group-form .form-group {
  margin-bottom: 20px;
}
.create-group-form label {
  display: block;
  margin-bottom: 6px;
  font-weight: 600; /* slightly bolder */
  color: #454545;
}
.create-group-form input[type="text"],
.create-group-form textarea,
.create-group-form select {
  width: 100%;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
  box-sizing: border-box;
  font-size: 1em;
}
.create-group-form input[type="file"] {
    padding: 7px;
}
.create-group-form textarea {
  min-height: 100px;
  resize: vertical;
}
.cover-preview-container {
  margin-top: 10px;
}
.cover-preview-small {
  max-width: 200px; /* 预览图大小 */
  max-height: 150px;
  border-radius: 4px;
  object-fit: contain;
  border: 1px solid #ddd;
}
.tags-selection {
  display: flex;
  flex-wrap: wrap;
  gap: 10px 15px;
  padding: 10px;
  border: 1px solid #eee;
  border-radius: 4px;
  margin-top: 5px;
}
.tag-item {
  display: flex;
  align-items: center;
}
.tag-item input[type="checkbox"] {
  margin-right: 6px;
  transform: scale(1.1);
  cursor: pointer;
}
.tag-item label {
  font-weight: normal;
  cursor: pointer;
  margin-bottom: 0; /* 修正label的margin */
}
.form-actions {
  margin-top: 30px;
  display: flex;
  gap: 15px;
  justify-content: flex-start;
}
.form-actions button, .form-actions .cancel-button {
  padding: 10px 25px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  font-size: 1em;
  font-weight: 500;
}
.form-actions button[type="submit"] {
  background-color: #28a745; /* 绿色 */
  color: white;
}
.form-actions button[type="submit"]:disabled {
  background-color: #aaa;
}
.form-actions .cancel-button {
  background-color: #f0f0f0;
  color: #555;
  border: 1px solid #ccc;
  text-decoration: none; /* 如果是router-link */
  line-height: normal; /* 对齐按钮 */
  display: inline-flex; /* 对齐按钮 */
  align-items: center; /* 对齐按钮 */
}
.error-message, .success-message {
  padding: 10px;
  margin-top: 15px;
  border-radius: 4px;
  font-size: 0.9em;
}
.error-message { background-color: #f8d7da; color: #721c24; border: 1px solid #f5c6cb;}
.error-text { /* 字段下方的小错误提示 */
    font-size: 0.8em;
    color: #dc3545;
    display: block;
    margin-top: 3px;
}
.success-message { background-color: #d4edda; color: #155724; border: 1px solid #c3e6cb;}
.loading-message-small { font-size: 0.9em; color: #777; }
</style>