<template>
  <div class="user-list-container page-container">
    <div class="header-bar">
      <h2>发现用户 (推荐)</h2> <!-- 标题注明是推荐 -->
    </div>

    <div v-if="isLoading" class="loading-message">正在加载推荐用户...</div>
    <div v-if="fetchError" class="error-message">{{ fetchError }}</div>
    
    <div v-if="!isLoading && users.length === 0 && !fetchError" class="empty-state">
      <p>目前没有用户推荐给您。</p>
      <p>尝试添加更多兴趣标签，或者稍后再来看看！</p>
    </div>

    <div v-if="users.length > 0" class="users-grid">
      <div v-for="user_profile in users" :key="user_profile.id" class="user-card">
        <router-link :to="{ name: 'UserProfileById', params: { id: user_profile.id } }" class="user-link">
          <div class="user-avatar-wrapper">
            <img 
              v-if="user_profile.avatar_url" 
              :src="user_profile.avatar_url" 
              :alt="(user_profile.nickname || user_profile.email) + '头像'" 
              class="user-avatar"
              @error="setDefaultAvatar"
            />
            <div v-else class="user-avatar-placeholder">
              <span>{{ user_profile.nickname ? user_profile.nickname.charAt(0).toUpperCase() : (user_profile.email ? user_profile.email.charAt(0).toUpperCase() : 'U') }}</span>
            </div>
          </div>
          <div class="user-card-content">
            <h3 class="user-nickname">{{ user_profile.nickname || user_profile.email }}</h3>
            <p v-if="user_profile.school" class="user-school">{{ user_profile.school }}</p>
            <!-- 显示共同兴趣标签 -->
            <div v-if="user_profile.common_interests_tags && user_profile.common_interests_tags.length > 0" class="common-tags-preview">
              <span v-for="tag in user_profile.common_interests_tags.slice(0,2)" :key="tag.id" class="tag-chip">
                {{ tag.name }}
              </span>
              <span v-if="user_profile.common_interests_tags.length > 2" class="tag-chip">...</span>
            </div>
          </div>
        </router-link>
      </div>
    </div>
    
    <!-- 推荐API通常不直接支持标准分页，除非后端特别实现 -->
    <!-- 所以我们暂时移除分页控件，或者根据推荐API的实际返回来调整 -->
    <!-- 
    <div v-if="pagination.totalPages > 1 && users.length > 0" class="pagination-controls">
      <button @click="fetchRecommendedUsers(pagination.currentPage - 1)" :disabled="!pagination.previous || isLoading">上一页</button>
      <span>第 {{ pagination.currentPage }} / {{ pagination.totalPages }} 页 (共 {{ pagination.count }} 用户)</span>
      <button @click="fetchRecommendedUsers(pagination.currentPage + 1)" :disabled="!pagination.next || isLoading">下一页</button>
    </div>
    -->
  </div>
</template>

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

const users = ref([]); // 将存储推荐的用户列表
const isLoading = ref(true);
const fetchError = ref('');
const authStore = useAuthStore(); // 推荐API通常需要认证

// 推荐API可能没有标准分页，所以这里的pagination意义不大，除非后端特别实现
const pagination = reactive({
    currentPage: 1,
    totalPages: 1,
    next: null,
    previous: null,
    count: 0,
});

const fetchRecommendedUsers = async (page = 1) => { // page参数可能对推荐API无效
  isLoading.value = true;
  fetchError.value = '';
  try {
    // 使用推荐API
    // 推荐API (/api/v1/accounts/users/recommendations/) 通常返回的是一个直接的列表，而不是分页对象
    const response = await apiClient.get('accounts/users/recommendations/'); 

    // 推荐API的响应结构可能直接是用户列表数组
    // 并且它应该已经排除了当前用户
    if (Array.isArray(response.data)) {
        users.value = response.data;
        pagination.count = response.data.length;
        pagination.totalPages = 1; // 假设推荐列表不分页或一次性返回
        pagination.currentPage = 1;
        pagination.next = null;
        pagination.previous = null;
    } else if (response.data && typeof response.data.count !== 'undefined' && Array.isArray(response.data.results)) {
        // 如果推荐API也返回了分页结构
        users.value = response.data.results;
        pagination.count = response.data.count;
        pagination.next = response.data.next;
        pagination.previous = response.data.previous;
        pagination.currentPage = page;
        const resultsLength = users.value.length;
        const pageSize = resultsLength > 0 ? resultsLength : (pagination.count > 0 ? pagination.count : 10);
        pagination.totalPages = Math.max(1, Math.ceil(pagination.count / pageSize));
    } else {
        console.warn("Unexpected response structure from recommendations API:", response.data);
        users.value = [];
        fetchError.value = '获取推荐用户失败，数据格式不正确。';
    }
    
  } catch (error) {
    console.error('获取推荐用户列表失败:', error.response || error);
    fetchError.value = '无法加载推荐用户。';
    if (error.response && error.response.status === 401) {
        fetchError.value = '请先登录以获取用户推荐。';
        // 可以考虑跳转到登录页
        // authStore.logout();
        // router.push('/login');
    }
  } finally {
    isLoading.value = false;
  }
};

// const truncateText = (text, maxLength) => { // 如果需要截断bio，取消注释
//   if (!text) return '';
//   if (text.length <= maxLength) return text;
//   return text.substring(0, maxLength) + '...';
// };

const setDefaultAvatar = (event) => {
  const placeholder = event.target.parentElement.querySelector('.user-avatar-placeholder');
  if (placeholder) placeholder.style.display = 'flex';
  event.target.style.display = 'none';
};

onMounted(() => {
  if (authStore.isAuthenticated) { // 推荐API通常需要登录
    fetchRecommendedUsers();
  } else {
    fetchError.value = '请先登录以查看用户推荐。';
    isLoading.value = false;
    // 可以考虑如果未登录则不加载此页面，或显示登录提示
  }
});
</script>

<style scoped>
.user-list-container { max-width: 1000px; margin: 20px auto; padding: 20px; }
.header-bar { display: flex; justify-content: space-between; align-items: center; margin-bottom: 25px; padding-bottom: 15px; border-bottom: 1px solid #e9ecef; }
.header-bar h2 { margin: 0; font-size: 2em; color: #343a40; }
.users-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); gap: 25px; }
.user-card { border: 1px solid #dee2e6; border-radius: 8px; background-color: #fff; padding: 20px; text-align: center; transition: all 0.3s ease-in-out; display: flex; flex-direction: column; }
.user-card:hover { transform: translateY(-5px); box-shadow: 0 8px 20px rgba(0,0,0,0.08); }
.user-link { text-decoration: none; color: inherit; display: flex; flex-direction: column; align-items: center; flex-grow: 1; }
.user-avatar-wrapper { margin-bottom: 12px; }
.user-avatar, .user-avatar-placeholder { width: 90px; height: 90px; border-radius: 50%; object-fit: cover; margin: 0 auto; background-color: #f1f3f5; display: flex; align-items: center; justify-content: center; font-size: 2.5em; color: #ced4da; border: 2px solid #fff; box-shadow: 0 1px 3px rgba(0,0,0,0.1); }
.user-card-content { text-align: center; flex-grow: 1; display: flex; flex-direction: column; justify-content: space-between; }
.user-nickname { font-size: 1.15em; font-weight: 600; margin-bottom: 5px; color: #212529; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.user-school { font-size: 0.85em; color: #6c757d; margin-bottom: 8px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.common-tags-preview {
    margin-top: 8px;
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    gap: 5px;
}
.tag-chip {
    background-color: #e9ecef;
    color: #495057;
    font-size: 0.75em;
    padding: 3px 8px;
    border-radius: 12px;
}
.loading-message, .error-message, .empty-state { text-align: center; padding: 40px 20px; color: #555; }
.empty-state a { color: #007bff; font-weight: bold; }
.pagination-controls { margin-top: 30px; text-align: center; }
.pagination-controls button { margin: 0 8px; padding: 8px 16px; cursor: pointer; border: 1px solid #ddd; background-color: #fff; border-radius: 4px; transition: background-color 0.2s; }
.pagination-controls button:disabled { opacity: 0.6; cursor: not-allowed; }
.pagination-controls button:hover:not(:disabled) { background-color: #e9ecef; }
.pagination-controls span { margin: 0 10px; color: #495057; }
.page-container { padding-bottom: 40px; }
</style>