<script setup lang="ts">
import { ref, computed } from 'vue'
import './database/database.css'

// 菜单类型
type MenuKey = 'users' | 'roles' | 'permissions'

// 当前选中的菜单
const activeMenu = ref<MenuKey>('users')

// 菜单列表
const menuItems = [
  { key: 'users', label: 'Users', icon: 'fa-users' },
  { key: 'roles', label: 'Roles', icon: 'fa-user-shield' },
  { key: 'permissions', label: 'Permissions', icon: 'fa-lock' },
]

// 用户数据
interface User {
  id: number
  name: string
  email: string
  role: string
  status: 'active' | 'inactive'
  createdAt: string
}

const users = ref<User[]>([
  { id: 1, name: 'Alex Smith', email: 'alex@example.com', role: 'Admin', status: 'active', createdAt: '2025-01-15' },
  { id: 2, name: 'John Doe', email: 'john@example.com', role: 'Developer', status: 'active', createdAt: '2025-02-20' },
  { id: 3, name: 'Jane Wilson', email: 'jane@example.com', role: 'Viewer', status: 'active', createdAt: '2025-03-05' },
  { id: 4, name: 'Mike Brown', email: 'mike@example.com', role: 'Developer', status: 'inactive', createdAt: '2025-03-10' },
  { id: 5, name: 'Sarah Davis', email: 'sarah@example.com', role: 'Admin', status: 'active', createdAt: '2025-03-15' },
])

// 角色数据
interface Role {
  id: number
  name: string
  description: string
  userCount: number
  permissions: string[]
}

const roles = ref<Role[]>([
  { id: 1, name: 'Admin', description: 'Full access to all features', userCount: 2, permissions: ['all'] },
  { id: 2, name: 'Developer', description: 'Access to development tools', userCount: 2, permissions: ['read', 'write', 'execute'] },
  { id: 3, name: 'Viewer', description: 'Read-only access', userCount: 1, permissions: ['read'] },
  { id: 4, name: 'Manager', description: 'Manage users and resources', userCount: 0, permissions: ['read', 'write', 'manage'] },
])

// 权限数据
interface Permission {
  id: string
  name: string
  description: string
  category: string
}

const permissions = ref<Permission[]>([
  { id: 'read', name: 'Read', description: 'View resources', category: 'General' },
  { id: 'write', name: 'Write', description: 'Create and update resources', category: 'General' },
  { id: 'delete', name: 'Delete', description: 'Remove resources', category: 'General' },
  { id: 'execute', name: 'Execute', description: 'Run scripts and tools', category: 'Tools' },
  { id: 'manage', name: 'Manage', description: 'Manage users and settings', category: 'Admin' },
  { id: 'all', name: 'All Access', description: 'Full system access', category: 'Admin' },
])

// 搜索和筛选
const searchQuery = ref('')
const filterRole = ref('')

// 编辑状态
const isEditingUser = ref(false)
const editingUser = ref<User | null>(null)
const isEditingRole = ref(false)
const editingRole = ref<Role | null>(null)
const isCreatingRole = ref(false)
const newRole = ref({ name: '', description: '' })

// 过滤后的用户
const filteredUsers = computed(() => {
  return users.value.filter(user => {
    const matchSearch = user.name.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
      user.email.toLowerCase().includes(searchQuery.value.toLowerCase())
    const matchRole = filterRole.value === '' || user.role === filterRole.value
    return matchSearch && matchRole
  })
})

// 获取用户角色选项
const roleOptions = computed(() => {
  return [...new Set(users.value.map(u => u.role))]
})

// 编辑用户
const openEditUser = (user: User) => {
  editingUser.value = { ...user }
  isEditingUser.value = true
}

const saveUser = () => {
  if (editingUser.value) {
    const index = users.value.findIndex(u => u.id === editingUser.value!.id)
    if (index !== -1) {
      users.value[index] = { ...editingUser.value }
    }
  }
  isEditingUser.value = false
}

// 删除用户
const deleteUser = (id: number) => {
  users.value = users.value.filter(u => u.id !== id)
}

// 切换用户状态
const toggleUserStatus = (user: User) => {
  user.status = user.status === 'active' ? 'inactive' : 'active'
}

// 编辑角色
const openEditRole = (role: Role) => {
  editingRole.value = { ...role }
  isEditingRole.value = true
}

const saveRole = () => {
  if (editingRole.value) {
    const index = roles.value.findIndex(r => r.id === editingRole.value!.id)
    if (index !== -1) {
      roles.value[index] = { ...editingRole.value }
    }
  }
  isEditingRole.value = false
}

// 删除角色
const deleteRole = (id: number) => {
  roles.value = roles.value.filter(r => r.id !== id)
}

// 创建角色
const openCreateRole = () => {
  newRole.value = { name: '', description: '' }
  isCreatingRole.value = true
}

const saveNewRole = () => {
  const newId = Math.max(...roles.value.map(r => r.id)) + 1
  roles.value.push({
    id: newId,
    name: newRole.value.name || 'New Role',
    description: newRole.value.description,
    userCount: 0,
    permissions: [],
  })
  isCreatingRole.value = false
}

// 状态样式
const statusClass = (status: string) => {
  return status === 'active' ? 'bg-primary-success' : 'bg-gray-500'
}
</script>

<template>
  <div class="p-6 min-h-screen">
    <!-- 页面标题 -->
    <div class="flex items-center gap-2 mb-6">
      <i class="fa-solid fa-user-shield text-orange-500"></i>
      <span class="font-medium">Account</span>
    </div>

    <div class="flex gap-6">
      <!-- 左侧菜单 -->
      <nav class="w-48 flex-shrink-0">
        <ul class="space-y-1">
          <li
            v-for="item in menuItems"
            :key="item.key"
            @click="activeMenu = item.key as MenuKey"
            class="px-4 py-3 rounded-lg cursor-pointer transition-colors flex items-center gap-3"
            :class="activeMenu === item.key
              ? 'bg-orange-500/10 text-orange-400'
              : 'text-gray-400 hover:bg-dark-600 hover:text-white'"
          >
            <i :class="['fa-solid', item.icon]"></i>
            <span>{{ item.label }}</span>
          </li>
        </ul>
      </nav>

      <!-- 右侧内容 -->
      <div class="flex-1">
        <!-- Users -->
        <div v-if="activeMenu === 'users'" class="space-y-4">
          <div class="flex items-center justify-between">
            <h2 class="text-xl font-semibold">Users</h2>
            <button class="bg-gradient-to-r from-primary-orange to-red-500 hover:from-orange-500 hover:to-red-600 text-white px-4 py-2 rounded-lg font-medium flex items-center gap-2 transition-all">
              <i class="fa-solid fa-plus"></i>
              Add User
            </button>
          </div>

          <!-- 搜索和筛选 -->
          <div class="flex gap-4">
            <div class="flex-1 relative">
              <i class="fa-solid fa-search absolute left-3 top-1/2 -translate-y-1/2 text-gray-400"></i>
              <input
                v-model="searchQuery"
                type="text"
                placeholder="Search users..."
                class="w-full bg-dark-600 border border-dark-500 rounded-lg py-2 pl-10 pr-4 text-white placeholder-gray-500 focus:outline-none focus:border-primary-orange"
              >
            </div>
            <el-select v-model="filterRole" placeholder="All Roles" class="w-40" size="large" popper-class="dark-select-dropdown">
              <el-option label="All Roles" value="" />
              <el-option v-for="role in roleOptions" :key="role" :label="role" :value="role" />
            </el-select>
          </div>

          <!-- 用户列表 -->
          <div class="bg-dark-700 rounded-xl overflow-hidden">
            <table class="w-full">
              <thead class="bg-dark-600">
                <tr>
                  <th class="text-left px-5 py-3 text-sm font-medium text-gray-400">User</th>
                  <th class="text-left px-5 py-3 text-sm font-medium text-gray-400">Role</th>
                  <th class="text-left px-5 py-3 text-sm font-medium text-gray-400">Status</th>
                  <th class="text-left px-5 py-3 text-sm font-medium text-gray-400">Created</th>
                  <th class="text-right px-5 py-3 text-sm font-medium text-gray-400">Actions</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="user in filteredUsers" :key="user.id" class="border-t border-dark-600 hover:bg-dark-600/50">
                  <td class="px-5 py-4">
                    <div class="flex items-center gap-3">
                      <div class="w-8 h-8 rounded-full bg-gradient-to-r from-orange-500 to-red-500 flex items-center justify-center text-white text-sm font-medium">
                        {{ user.name.charAt(0) }}
                      </div>
                      <div>
                        <div class="font-medium">{{ user.name }}</div>
                        <div class="text-sm text-gray-500">{{ user.email }}</div>
                      </div>
                    </div>
                  </td>
                  <td class="px-5 py-4">
                    <span class="bg-dark-500 px-2 py-1 rounded text-sm">{{ user.role }}</span>
                  </td>
                  <td class="px-5 py-4">
                    <div class="flex items-center gap-2">
                      <span class="w-2 h-2 rounded-full" :class="statusClass(user.status)"></span>
                      <span class="capitalize text-sm">{{ user.status }}</span>
                    </div>
                  </td>
                  <td class="px-5 py-4 text-gray-400 text-sm">{{ user.createdAt }}</td>
                  <td class="px-5 py-4">
                    <div class="flex items-center justify-end gap-2">
                      <button
                        @click="toggleUserStatus(user)"
                        class="p-2 rounded-lg hover:bg-dark-500 transition-colors"
                        :title="user.status === 'active' ? 'Deactivate' : 'Activate'"
                      >
                        <i :class="['fa-solid', user.status === 'active' ? 'fa-ban' : 'fa-check', 'text-gray-400 hover:text-white']"></i>
                      </button>
                      <button
                        @click="openEditUser(user)"
                        class="p-2 rounded-lg hover:bg-dark-500 transition-colors"
                        title="Edit"
                      >
                        <i class="fa-solid fa-pen text-gray-400 hover:text-white"></i>
                      </button>
                      <button
                        @click="deleteUser(user.id)"
                        class="p-2 rounded-lg hover:bg-dark-500 transition-colors"
                        title="Delete"
                      >
                        <i class="fa-solid fa-trash text-gray-400 hover:text-red-400"></i>
                      </button>
                    </div>
                  </td>
                </tr>
              </tbody>
            </table>

            <div v-if="filteredUsers.length === 0" class="py-12 text-center text-gray-500">
              <i class="fa-solid fa-users text-4xl mb-3"></i>
              <p>No users found</p>
            </div>
          </div>
        </div>

        <!-- Roles -->
        <div v-if="activeMenu === 'roles'" class="space-y-4">
          <div class="flex items-center justify-between">
            <h2 class="text-xl font-semibold">Roles</h2>
            <button @click="openCreateRole" class="bg-gradient-to-r from-primary-orange to-red-500 hover:from-orange-500 hover:to-red-600 text-white px-4 py-2 rounded-lg font-medium flex items-center gap-2 transition-all">
              <i class="fa-solid fa-plus"></i>
              Add Role
            </button>
          </div>

          <!-- 角色列表 -->
          <div class="grid grid-cols-2 gap-4">
            <div v-for="role in roles" :key="role.id" class="bg-dark-700 rounded-xl p-5 border border-dark-600">
              <div class="flex items-start justify-between mb-3">
                <div>
                  <h3 class="font-semibold text-lg">{{ role.name }}</h3>
                  <p class="text-sm text-gray-400">{{ role.description }}</p>
                </div>
                <div class="flex gap-1">
                  <button @click="openEditRole(role)" class="p-2 rounded-lg hover:bg-dark-600 transition-colors">
                    <i class="fa-solid fa-pen text-gray-400 hover:text-white"></i>
                  </button>
                  <button @click="deleteRole(role.id)" class="p-2 rounded-lg hover:bg-dark-600 transition-colors">
                    <i class="fa-solid fa-trash text-gray-400 hover:text-red-400"></i>
                  </button>
                </div>
              </div>
              <div class="flex items-center justify-between">
                <div class="flex flex-wrap gap-1">
                  <span v-for="perm in role.permissions.slice(0, 3)" :key="perm" class="px-2 py-0.5 bg-dark-600 rounded text-xs text-gray-400">
                    {{ perm }}
                  </span>
                  <span v-if="role.permissions.length > 3" class="px-2 py-0.5 bg-dark-600 rounded text-xs text-gray-400">
                    +{{ role.permissions.length - 3 }}
                  </span>
                </div>
                <span class="text-sm text-gray-400">{{ role.userCount }} users</span>
              </div>
            </div>
          </div>
        </div>

        <!-- Permissions -->
        <div v-if="activeMenu === 'permissions'" class="space-y-4">
          <div class="flex items-center justify-between">
            <h2 class="text-xl font-semibold">Permissions</h2>
          </div>

          <div class="bg-dark-700 rounded-xl overflow-hidden">
            <table class="w-full">
              <thead class="bg-dark-600">
                <tr>
                  <th class="text-left px-5 py-3 text-sm font-medium text-gray-400">Permission</th>
                  <th class="text-left px-5 py-3 text-sm font-medium text-gray-400">Description</th>
                  <th class="text-left px-5 py-3 text-sm font-medium text-gray-400">Category</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="perm in permissions" :key="perm.id" class="border-t border-dark-600 hover:bg-dark-600/50">
                  <td class="px-5 py-4">
                    <span class="font-medium">{{ perm.name }}</span>
                    <span class="text-gray-500 ml-2">({{ perm.id }})</span>
                  </td>
                  <td class="px-5 py-4 text-gray-400">{{ perm.description }}</td>
                  <td class="px-5 py-4">
                    <span class="px-2 py-1 bg-dark-500 rounded text-sm">{{ perm.category }}</span>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>

    <!-- 编辑用户弹窗 -->
    <Teleport to="body">
      <div v-if="isEditingUser" class="fixed inset-0 bg-black/60 flex items-center justify-center z-50">
        <div class="bg-dark-700 rounded-2xl w-full max-w-lg border border-dark-500 shadow-2xl">
          <div class="flex items-center justify-between p-5 border-b border-dark-500">
            <h3 class="text-lg font-semibold">Edit User</h3>
            <button @click="isEditingUser = false" class="text-gray-400 hover:text-white transition-colors">
              <i class="fa-solid fa-xmark text-xl"></i>
            </button>
          </div>

          <div class="p-5 space-y-4">
            <div>
              <label class="block text-sm font-medium text-gray-300 mb-2">Name</label>
              <input
                v-model="editingUser!.name"
                type="text"
                class="w-full bg-dark-600 border border-dark-500 rounded-lg px-4 py-2.5 text-white focus:outline-none focus:border-primary-orange"
              >
            </div>

            <div>
              <label class="block text-sm font-medium text-gray-300 mb-2">Email</label>
              <input
                v-model="editingUser!.email"
                type="email"
                class="w-full bg-dark-600 border border-dark-500 rounded-lg px-4 py-2.5 text-white focus:outline-none focus:border-primary-orange"
              >
            </div>

            <div>
              <label class="block text-sm font-medium text-gray-300 mb-2">Role</label>
              <el-select v-model="editingUser!.role" placeholder="Select" class="w-full" size="large" popper-class="dark-select-dropdown">
                <el-option v-for="role in roleOptions" :key="role" :label="role" :value="role" />
              </el-select>
            </div>

            <div>
              <label class="block text-sm font-medium text-gray-300 mb-2">Status</label>
              <el-select v-model="editingUser!.status" placeholder="Select" class="w-full" size="large" popper-class="dark-select-dropdown">
                <el-option label="Active" value="active" />
                <el-option label="Inactive" value="inactive" />
              </el-select>
            </div>
          </div>

          <div class="flex items-center justify-end gap-3 p-5 border-t border-dark-500">
            <button
              @click="isEditingUser = false"
              class="px-4 py-2 rounded-lg bg-dark-600 text-gray-300 hover:bg-dark-500 transition-colors"
            >
              Cancel
            </button>
            <button
              @click="saveUser"
              class="px-4 py-2 rounded-lg bg-gradient-to-r from-primary-orange to-red-500 text-white hover:from-orange-500 hover:to-red-600 transition-all"
            >
              Save Changes
            </button>
          </div>
        </div>
      </div>
    </Teleport>

    <!-- 创建角色弹窗 -->
    <Teleport to="body">
      <div v-if="isCreatingRole" class="fixed inset-0 bg-black/60 flex items-center justify-center z-50">
        <div class="bg-dark-700 rounded-2xl w-full max-w-lg border border-dark-500 shadow-2xl">
          <div class="flex items-center justify-between p-5 border-b border-dark-500">
            <h3 class="text-lg font-semibold">Create Role</h3>
            <button @click="isCreatingRole = false" class="text-gray-400 hover:text-white transition-colors">
              <i class="fa-solid fa-xmark text-xl"></i>
            </button>
          </div>

          <div class="p-5 space-y-4">
            <div>
              <label class="block text-sm font-medium text-gray-300 mb-2">Role Name</label>
              <input
                v-model="newRole.name"
                type="text"
                placeholder="Enter role name..."
                class="w-full bg-dark-600 border border-dark-500 rounded-lg px-4 py-2.5 text-white placeholder-gray-500 focus:outline-none focus:border-primary-orange"
              >
            </div>

            <div>
              <label class="block text-sm font-medium text-gray-300 mb-2">Description</label>
              <textarea
                v-model="newRole.description"
                rows="3"
                placeholder="Describe this role..."
                class="w-full bg-dark-600 border border-dark-500 rounded-lg px-4 py-2.5 text-white placeholder-gray-500 focus:outline-none focus:border-primary-orange resize-none"
              ></textarea>
            </div>
          </div>

          <div class="flex items-center justify-end gap-3 p-5 border-t border-dark-500">
            <button
              @click="isCreatingRole = false"
              class="px-4 py-2 rounded-lg bg-dark-600 text-gray-300 hover:bg-dark-500 transition-colors"
            >
              Cancel
            </button>
            <button
              @click="saveNewRole"
              class="px-4 py-2 rounded-lg bg-gradient-to-r from-primary-orange to-red-500 text-white hover:from-orange-500 hover:to-red-600 transition-all"
            >
              Create Role
            </button>
          </div>
        </div>
      </div>
    </Teleport>
  </div>
</template>
