<template>
  <div class="roles-container">
    <div class="page-header">
      <h1 class="page-title">角色管理</h1>
      <button class="create-btn" @click="router.push('/admin/roles/create')">
        <span class="btn-icon">+</span>
        <span class="btn-text">新建角色</span>
      </button>
    </div>
    
    <!-- Search -->
    <div class="search-box">
      <input 
        type="text" 
        placeholder="搜索角色名称" 
        v-model="searchQuery"
        @input="handleSearch"
      />
      <button class="search-btn">🔍</button>
    </div>
    
    <!-- Roles Table -->
    <div class="table-container">
      <table class="roles-table">
        <thead>
          <tr>
            <th>ID</th>
            <th>角色名称</th>
            <th>描述</th>
            <th>创建时间</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="role in filteredRoles" :key="role.id">
            <td>{{ role.id }}</td>
            <td>{{ role.name }}</td>
            <td>{{ role.description || '无描述' }}</td>
            <td>{{ formatDate(role.createdAt) }}</td>
            <td class="actions">
              <button class="action-btn edit" @click="router.push(`/admin/roles/${role.id}/edit`)" title="编辑">
                ✏️
              </button>
              <button class="action-btn delete" @click="handleDelete(role.id)" title="删除">
                🗑️
              </button>
            </td>
          </tr>
        </tbody>
      </table>
      
      <!-- Empty State -->
      <div class="empty-state" v-if="filteredRoles.length === 0">
        <div class="empty-icon">🔒</div>
        <h3>暂无角色数据</h3>
        <p>点击右上角按钮创建新角色</p>
      </div>
    </div>
    
    <!-- Pagination -->
    <div class="pagination" v-if="filteredRoles.length > 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 } from 'vue'
import { useRouter } from 'vue-router'
import { useToast } from '../../composables/useToast'
import { getRoles, deleteRole, Role } from '../../services/api'

const router = useRouter()
const toast = useToast()

// State
const roles = ref<Role[]>([])
const searchQuery = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const isLoading = ref(false)

// Computed properties
const filteredRoles = computed(() => {
  let result = roles.value
  
  // Apply search filter
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    result = result.filter(role => 
      role.name.toLowerCase().includes(query) ||
      (role.description && role.description.toLowerCase().includes(query))
    )
  }
  
  return result
})

const totalPages = computed(() => {
  return Math.ceil(filteredRoles.value.length / pageSize.value)
})

// Methods
const fetchRoles = async () => {
  isLoading.value = true
  try {
    const data = await getRoles()
    roles.value = data
  } catch (error) {
    toast.error('获取角色列表失败')
    console.error('Error fetching roles:', error)
  } finally {
    isLoading.value = false
  }
}

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

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

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(() => {
  fetchRoles()
})
</script>

<style scoped>
.roles-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: rgba(212, 179, 131, 0.1);
  color: #d4b383;
  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;
  transform: translateY(-1px);
  box-shadow: 0 0 15px rgba(212, 179, 131, 0.3);
}

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

/* Search */
.search-box {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  margin-bottom: 1.5rem;
  max-width: 400px;
}

.search-box input {
  padding: 0.75rem;
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 0.5rem;
  flex: 1;
  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.4);
}

.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;
}

/* 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);
}

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

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

.roles-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;
}

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

/* 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;
  background: rgba(255, 255, 255, 0.05);
  border-color: rgba(255, 255, 255, 0.1);
}

.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-box {
    max-width: 100%;
  }
  
  .roles-table {
    display: block;
    overflow-x: auto;
  }
  
  .roles-table th,
  .roles-table td {
    white-space: nowrap;
  }
}
</style>
