/**
 * User Management View
 * Refactored with semantic variables and native feature integration
 */

import { adminApi } from '../api/admin.js';

const { ref, onMounted } = Vue;

export default {
  name: 'UserManagement',
  template: `
    <div class="user-management">
      <div class="page-header">
        <h2>用户管理</h2>
        <div class="actions">
          <button class="btn btn-primary" @click="showAddModal = true">添加用户</button>
        </div>
      </div>

      <div class="filter-bar">
        <input type="text" v-model="searchQuery" placeholder="搜索邮箱..." @input="handleSearch" />
      </div>

      <div class="table-container">
        <table class="admin-table">
          <thead>
            <tr>
              <th>ID</th>
              <th>用户邮箱</th>
              <th>已分配流量</th>
              <th>剩余流量</th>
              <th>到期时间</th>
              <th>状态</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="user in userList" :key="user.id">
              <td>{{ user.id }}</td>
              <td>
                <div class="email-cell">
                  <span>{{ user.email }}</span>
                  <span v-if="user.online_ip" class="online-ip-badge" :title="'实时连接IP: ' + user.online_ip">
                    IP: {{ user.online_ip }}
                  </span>
                </div>
              </td>
              <td>{{ formatTraffic(user.transfer_enable) }}</td>
              <td>{{ formatTraffic(user.transfer_enable - (user.u + user.d)) }}</td>
              <td>{{ formatDate(user.expired_at) }}</td>
              <td>
                <span :class="'status-tag ' + (user.enable ? 'status-active' : 'status-disabled')">
                  {{ user.enable ? '启用' : '禁用' }}
                </span>
              </td>
              <td>
                <div class="row-actions">
                  <a href="javascript:;" @click="editUser(user)">编辑</a>
                  <span class="sep">|</span>
                  <a href="javascript:;" class="text-danger" @click="deleteUser(user)">删除</a>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
      </div>

      <div v-if="loading" class="loading">加载中...</div>
    </div>
  `,
  setup() {
    const userList = ref([]);
    const loading = ref(true);
    const searchQuery = ref('');
    const showAddModal = ref(false);

    const loadUsers = async () => {
      loading.value = true;
      try {
        const res = await adminApi.fetchUsers({ email: searchQuery.value });
        // Variable-level refactoring: internal logic uses semantic names
        // If the backend returns 'list', we mapping it.
        userList.value = res.data.list || res.list || [];
      } catch (e) {
        console.error('Failed to load users', e);
      } finally {
        loading.value = false;
      }
    };

    const handleSearch = debounce(() => {
      loadUsers();
    }, 500);

    const formatTraffic = (bytes) => {
        if (!bytes || bytes < 0) return '0 B';
        const k = 1024;
        const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    };

    const formatDate = (timestamp) => {
      if (!timestamp) return '永不过期';
      if (timestamp < 1000000000) return '已过期'; // Simplified
      return new Date(timestamp * 1000).toLocaleString();
    };

    const editUser = (user) => {
      console.log('Edit user:', user.email);
    };

    const deleteUser = (user) => {
      if (confirm(`确定要删除用户 ${user.email} 吗?`)) {
        adminApi.deleteUser(user.id).then(() => loadUsers());
      }
    };

    onMounted(loadUsers);

    return {
      userList,
      loading,
      searchQuery,
      handleSearch,
      formatTraffic,
      formatDate,
      editUser,
      deleteUser
    };
  }
};

function debounce(fn, delay) {
  let timer = null;
  return function() {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => fn.apply(this, arguments), delay);
  };
}
