<template>
  <div class="users-container">
    <div class="page-header">
      <h1 class="page-title">用户管理</h1>
      <button class="create-btn" @click="router.push('/admin/users/create')">
        <span class="btn-icon">+</span>
        <span class="btn-text">新建用户</span>
      </button>
    </div>
    
    <!-- Search and Filter -->
    <AdminTableFilter
      v-model:keyword="searchQuery"
      keyword-placeholder="搜索用户名或邮箱"
      @search="handleSearch"
      @reset="resetFilters"
    >
      <template #filters>
        <div class="filter-field">
          <label>角色</label>
          <CustomSelect v-model="roleFilter" :options="roleFilterOptions" style="width: 120px;" />
        </div>
        <div class="filter-field">
          <label>状态</label>
          <CustomSelect v-model="statusFilter" :options="statusFilterOptions" style="width: 120px;" />
        </div>
      </template>
    </AdminTableFilter>
    
    <!-- Users Table -->
    <div class="table-container">
      <table class="users-table">
        <thead>
          <tr>
            <th>ID</th>
            <th>头像</th>
            <th>用户名</th>
            <th>邮箱</th>
            <th>角色</th>
            <th>状态</th>
            <th>创建时间</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="user in users" :key="user.id">
            <td>{{ user.id }}</td>
            <td>
              <div class="user-avatar-cell">
                <img
                  v-if="user.avatar"
                  :src="user.avatar"
                  :alt="user.username"
                  class="user-avatar-img"
                />
                <span v-else class="user-avatar-placeholder">{{ user.username.charAt(0).toUpperCase() }}</span>
              </div>
            </td>
            <td>{{ user.username }}</td>
            <td>
              <button type="button" class="email-link" @click="openUserProfile(user.id)">{{ user.email }}</button>
            </td>
            <td>
              <span class="role-badge" :class="user.role">
                {{ getUserRoleText(user.role) }}
              </span>
            </td>
            <td>
              <span class="status-badge" :class="user.isActive ? 'active' : 'inactive'">
                {{ user.isActive ? '激活' : '禁用' }}
              </span>
            </td>
            <td>{{ formatDate(user.createdAt) }}</td>
            <td class="actions">
              <button class="action-btn edit" @click="router.push(`/admin/users/${user.id}/edit`)" title="编辑">
                ✏️
              </button>
              <button class="action-btn delete" @click="handleDelete(user.id)" title="删除">
                🗑️
              </button>
            </td>
          </tr>
        </tbody>
      </table>
      
      <!-- Empty State -->
      <div class="empty-state" v-if="!isLoading && users.length === 0">
        <div class="empty-icon">👥</div>
        <h3>暂无用户数据</h3>
        <p>点击右上角按钮创建新用户</p>
      </div>
    </div>
    
    <!-- Pagination -->
    <div class="pagination" v-if="total > 0">
      <button class="page-btn" @click="currentPage--" :disabled="currentPage === 1">
        上一页
      </button>
      <span class="page-info">
        第 {{ currentPage }} / {{ totalPages }} 页
      </span>
      <button class="page-btn" @click="currentPage++" :disabled="currentPage === totalPages">
        下一页
      </button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useToast } from '../../composables/useToast'
import { getUsersPaginated, deleteUser, User } from '../../services/api'
import CustomSelect from '../../components/CustomSelect.vue'
import AdminTableFilter from '../../components/admin/AdminTableFilter.vue'
import { useUserProfileModal } from '../../composables/useUserProfileModal'

const router = useRouter()
const toast = useToast()
const { openUserProfile } = useUserProfileModal()

// State
const users = ref<User[]>([])
const searchQuery = ref('')
const roleFilter = ref('')
const statusFilter = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const isLoading = ref(false)

// Select options
const roleFilterOptions = [
  { value: '', label: '全部角色' },
  { value: 'admin', label: '管理员' },
  { value: 'editor', label: '编辑' },
  { value: 'viewer', label: '查看者' }
]

const statusFilterOptions = [
  { value: '', label: '全部状态' },
  { value: '1', label: '激活' },
  { value: '0', label: '禁用' }
]

const totalPages = computed(() => Math.max(1, Math.ceil(total.value / pageSize.value)))

const fetchUsers = async () => {
  isLoading.value = true
  try {
    const params: Parameters<typeof getUsersPaginated>[0] = {
      page: currentPage.value,
      pageSize: pageSize.value,
      keyword: searchQuery.value.trim() || undefined,
      role: roleFilter.value || undefined,
    }
    if (statusFilter.value !== '') {
      params.isActive = parseInt(statusFilter.value)
    }
    const data = await getUsersPaginated(params)
    users.value = data.list
    total.value = data.total
  } catch (error) {
    toast.error('获取用户列表失败')
    console.error('Error fetching users:', error)
  } finally {
    isLoading.value = false
  }
}

const handleSearch = () => {
  currentPage.value = 1
  fetchUsers()
}

const resetFilters = () => {
  searchQuery.value = ''
  roleFilter.value = ''
  statusFilter.value = ''
  currentPage.value = 1
  fetchUsers()
}

watch(currentPage, () => {
  fetchUsers()
})

const handleDelete = async (id: number) => {
  if (confirm('确定要删除这个用户吗？')) {
    try {
      await deleteUser(id)
      toast.success('用户删除成功')
      fetchUsers() // Refresh the list
    } catch (error) {
      toast.error('删除用户失败')
      console.error('Error deleting user:', error)
    }
  }
}

const getUserRoleText = (role: string): string => {
  const roleMap: Record<string, string> = {
    'admin': '管理员',
    'editor': '编辑',
    'viewer': '查看者'
  }
  return roleMap[role] || role
}

const formatDate = (dateString: string): string => {
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// Lifecycle
onMounted(() => {
  fetchUsers()
})
</script>

<style scoped>
.users-container {
  width: 100%;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1.5rem;
}

.page-title {
  font-size: 1.75rem;
  font-weight: 600;
  color: #d4b383;
  margin: 0;
  font-family: 'Inter', sans-serif;
}

.create-btn {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.75rem 1.5rem;
  background-color: #d4b383;
  color: #050505;
  border: 1px solid #d4b383;
  border-radius: 0.5rem;
  cursor: pointer;
  font-weight: 500;
  transition: all 0.3s cubic-bezier(0.16, 1, 0.3, 1);
  font-family: 'Inter', sans-serif;
}

.create-btn:hover {
  background-color: transparent;
  color: #d4b383;
  transform: translateY(-1px);
  box-shadow: 0 0 15px rgba(212, 179, 131, 0.3);
}

.btn-icon {
  font-size: 1.25rem;
}

/* Search and Filter */
.search-filter {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1.5rem;
  flex-wrap: wrap;
  gap: 1rem;
}

.search-box {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.search-box input {
  padding: 0.75rem;
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 0.5rem;
  width: 300px;
  font-size: 0.95rem;
  background: rgba(255, 255, 255, 0.05);
  color: white;
  font-family: 'Inter', sans-serif;
}

.search-box input::placeholder {
  color: rgba(255, 255, 255, 0.5);
}

.search-box input:focus {
  outline: none;
  border-color: #d4b383;
  box-shadow: 0 0 0 3px rgba(212, 179, 131, 0.2);
}

.search-btn {
  padding: 0.75rem;
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 0.5rem;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.16, 1, 0.3, 1);
  color: rgba(255, 255, 255, 0.8);
}

.search-btn:hover {
  background: rgba(212, 179, 131, 0.1);
  border-color: #d4b383;
  color: #d4b383;
}

.filter-options {
  display: flex;
  gap: 1rem;
}

.filter-options select {
  padding: 0.75rem;
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 0.5rem;
  font-size: 0.95rem;
  background: rgba(255, 255, 255, 0.05);
  color: white;
  cursor: pointer;
  font-family: 'Inter', sans-serif;
}

.filter-options select:focus {
  outline: none;
  border-color: #d4b383;
  box-shadow: 0 0 0 3px rgba(212, 179, 131, 0.2);
}

/* Table Styles */
.table-container {
  background: rgba(255, 255, 255, 0.05);
  backdrop-filter: blur(10px);
  -webkit-backdrop-filter: blur(10px);
  border-radius: 0.5rem;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  margin-bottom: 1.5rem;
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.users-table {
  width: 100%;
  border-collapse: collapse;
  color: white;
}

.users-table th,
.users-table td {
  padding: 1rem;
  text-align: left;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  font-family: 'Inter', sans-serif;
}

.users-table th {
  background: rgba(255, 255, 255, 0.08);
  font-weight: 600;
  color: #d4b383;
  font-size: 0.875rem;
  text-transform: uppercase;
  letter-spacing: 0.05em;
}

.users-table tr:hover {
  background: rgba(212, 179, 131, 0.05);
}

.email-link {
  background: none;
  border: none;
  padding: 0;
  color: #d4b383;
  cursor: pointer;
  font: inherit;
  text-decoration: underline;
  text-underline-offset: 2px;
}

.email-link:hover {
  color: #fff;
}

/* Avatar */
.user-avatar-cell {
  display: flex;
  align-items: center;
  justify-content: center;
}

.user-avatar-img,
.user-avatar-placeholder {
  width: 2rem;
  height: 2rem;
  border-radius: 9999px;
  object-fit: cover;
}

.user-avatar-placeholder {
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(212, 179, 131, 0.15);
  color: #d4b383;
  font-size: 0.875rem;
  font-weight: 600;
  border: 1px solid rgba(212, 179, 131, 0.25);
}

/* Badges */
.role-badge {
  padding: 0.25rem 0.75rem;
  border-radius: 9999px;
  font-size: 0.8rem;
  font-weight: 500;
  text-transform: uppercase;
  letter-spacing: 0.05em;
  border: 1px solid transparent;
}

.role-badge.admin {
  background-color: rgba(59, 130, 246, 0.2);
  color: #3b82f6;
  border-color: rgba(59, 130, 246, 0.3);
}

.role-badge.editor {
  background-color: rgba(16, 185, 129, 0.2);
  color: #10b981;
  border-color: rgba(16, 185, 129, 0.3);
}

.role-badge.viewer {
  background-color: rgba(251, 191, 36, 0.2);
  color: #f59e0b;
  border-color: rgba(251, 191, 36, 0.3);
}

.status-badge {
  padding: 0.25rem 0.75rem;
  border-radius: 9999px;
  font-size: 0.8rem;
  font-weight: 500;
  text-transform: uppercase;
  letter-spacing: 0.05em;
  border: 1px solid transparent;
}

.status-badge.active {
  background-color: rgba(16, 185, 129, 0.2);
  color: #10b981;
  border-color: rgba(16, 185, 129, 0.3);
}

.status-badge.inactive {
  background-color: rgba(239, 68, 68, 0.2);
  color: #ef4444;
  border-color: rgba(239, 68, 68, 0.3);
}

/* Actions */
.actions {
  display: flex;
  gap: 0.5rem;
}

.action-btn {
  padding: 0.5rem;
  border: 1px solid transparent;
  border-radius: 0.375rem;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.16, 1, 0.3, 1);
  font-size: 1rem;
  display: flex;
  align-items: center;
  justify-content: center;
}

.action-btn.edit {
  background-color: rgba(212, 179, 131, 0.2);
  color: #d4b383;
  border-color: rgba(212, 179, 131, 0.3);
}

.action-btn.edit:hover {
  background-color: rgba(212, 179, 131, 0.3);
  border-color: #d4b383;
  box-shadow: 0 0 10px rgba(212, 179, 131, 0.3);
}

.action-btn.delete {
  background-color: rgba(239, 68, 68, 0.2);
  color: #ef4444;
  border-color: rgba(239, 68, 68, 0.3);
}

.action-btn.delete:hover {
  background-color: rgba(239, 68, 68, 0.3);
  border-color: #ef4444;
  box-shadow: 0 0 10px rgba(239, 68, 68, 0.3);
}

/* Empty State */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 4rem 2rem;
  text-align: center;
  color: rgba(255, 255, 255, 0.6);
}

.empty-icon {
  font-size: 4rem;
  margin-bottom: 1rem;
  color: #d4b383;
}

.empty-state h3 {
  font-size: 1.25rem;
  font-weight: 600;
  margin: 0 0 0.5rem 0;
  color: white;
  font-family: 'Inter', sans-serif;
}

.empty-state p {
  margin: 0;
  font-size: 0.95rem;
  font-family: 'Inter', sans-serif;
}

/* Pagination */
.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 1rem;
}

.page-btn {
  padding: 0.5rem 1rem;
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 0.5rem;
  cursor: pointer;
  font-weight: 500;
  transition: all 0.3s cubic-bezier(0.16, 1, 0.3, 1);
  color: rgba(255, 255, 255, 0.8);
  font-family: 'Inter', sans-serif;
}

.page-btn:hover:not(:disabled) {
  background: rgba(212, 179, 131, 0.1);
  border-color: #d4b383;
  color: #d4b383;
}

.page-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.page-info {
  font-size: 0.95rem;
  color: rgba(255, 255, 255, 0.6);
  font-family: 'Inter', sans-serif;
}

/* Responsive Design */
@media (max-width: 768px) {
  .search-filter {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-box input {
    width: 100%;
  }
  
  .filter-options {
    flex-direction: column;
  }
  
  .users-table {
    display: block;
    overflow-x: auto;
  }
  
  .users-table th,
  .users-table td {
    white-space: nowrap;
  }
}
</style>
