<template>
  <div class="stats-info mb-4">
    <div class="stat-item">
      <div class="stat-value">{{ formatBytes(stats.totalReceived) }}</div>
      <div class="stat-label">Total Received</div>
    </div>
    <div class="stat-item">
      <div class="stat-value">{{ formatBytes(stats.totalSent) }}</div>
      <div class="stat-label">Total Sent</div>
    </div>
    <div class="stat-item">
      <div class="stat-value">{{ stats.activeClients }}</div>
      <div class="stat-label">Active Clients</div>
    </div>
  </div>

  <div class="d-flex justify-content-between align-items-center mb-3 flex-wrap gap-3">
    <div class="d-flex gap-3 align-items-center flex-wrap">
      <div class="sort-btn-group">
        <button class="sort-btn" :class="{ active: currentSort === 'received' }"
          @click="currentSort = 'received'">Received</button>
        <button class="sort-btn" :class="{ active: currentSort === 'sent' }"
          @click="currentSort = 'sent'">Sent</button>
      </div>

      <div class="input-group input-group-sm" style="width: 250px;">
        <span class="input-group-text"><i class="fas fa-search"></i></span>
        <input type="text" class="form-control" placeholder="Search client..." v-model="searchQuery">
      </div>
    </div>

    <div class="form-check form-switch">
      <input class="form-check-input" type="checkbox" id="hideDisconnected" v-model="hideDisconnected">
      <label class="form-check-label user-select-none text-muted" for="hideDisconnected">Hide Disconnected</label>
    </div>
  </div>

  <div class="card">
    <div class="card-header d-flex justify-content-between align-items-center">
      <span><i class="fas fa-network-wired me-2"></i>Clients List</span>
      <small class="text-muted">Updated: {{ lastUpdated }}</small>
    </div>
    <div class="table-responsive">
      <table class="table table-hover mb-0">
        <thead>
          <tr>
            <th>Client Name</th>
            <th>Real Address</th>
            <th>Status</th>
            <th @click="currentSort = 'received'" class="cursor-pointer" :class="{'active-sort': currentSort === 'received'}">
              Received <i v-if="currentSort === 'received'" class="fas fa-sort-down ms-1"></i>
            </th>
            <th @click="currentSort = 'sent'" class="cursor-pointer" :class="{'active-sort': currentSort === 'sent'}">
              Sent <i v-if="currentSort === 'sent'" class="fas fa-sort-down ms-1"></i>
            </th>
            <th>Down Speed</th>
            <th>Up Speed</th>
            <th>Last Activity</th>
          </tr>
        </thead>
        <tbody>
          <tr v-if="loading && clients.length === 0">
            <td colspan="8" class="text-center py-4 text-muted">Loading...</td>
          </tr>
          <tr v-else-if="filteredClients.length === 0">
            <td colspan="8" class="text-center py-4 text-muted">No clients match your filter</td>
          </tr>
          <template v-else>
            <template v-for="(group, index) in groupedClients" :key="index">
              <tr class="section-divider">
                <td colspan="8">
                  <i class="fas me-2 small" :class="group.status === 'Active' ? 'fa-circle text-success' : 'fa-circle text-danger'"></i>
                  {{ group.status }} Clients
                </td>
              </tr>
              <tr v-for="c in group.items" :key="c.common_name">
                <td>
                  <a @click="openHistory(c.common_name)" class="client-link">
                    {{ c.common_name }} <i class="fas fa-chart-area ms-1 small opacity-50"></i>
                  </a>
                </td>
                <td class="small text-muted">{{ c.real_address || '-' }}</td>
                <td>
                  <span class="status-badge" :class="c.status === 'Active' ? 'status-active' : 'status-disconnected'">
                    {{ c.status }}
                  </span>
                </td>
                <td class="font-monospace small">{{ formatBytes(c.total_bytes_received) }}</td>
                <td class="font-monospace small">{{ formatBytes(c.total_bytes_sent) }}</td>
                
                <td class="font-monospace small">
                    <span v-if="c.status === 'Active'" :class="c.current_recv_rate_mbps > 0.01 ? 'text-success fw-bold' : 'text-muted opacity-75'">
                        {{ c.current_recv_rate_mbps ? formatRate(c.current_recv_rate_mbps) : '0.000 Mbps' }}
                    </span>
                    <span v-else class="text-muted opacity-25">-</span>
                </td>
                
                <td class="font-monospace small">
                    <span v-if="c.status === 'Active'" :class="c.current_sent_rate_mbps > 0.01 ? 'text-primary fw-bold' : 'text-muted opacity-75'">
                        {{ c.current_sent_rate_mbps ? formatRate(c.current_sent_rate_mbps) : '0.000 Mbps' }}
                    </span>
                    <span v-else class="text-muted opacity-25">-</span>
                </td>
                
                <td class="small text-muted">{{ formatDate(c.last_activity) }}</td>
              </tr>
            </template>
          </template>
        </tbody>
      </table>
    </div>
  </div>

  <HistoryModal ref="historyModal" />
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue';
import { useApi } from '../composables/useApi';
import { useFormatters } from '../composables/useFormatters';
import HistoryModal from '../components/HistoryModal.vue';
import { useAppConfig } from '../composables/useAppConfig';

const { fetchStats, apiClient } = useApi();
const { formatBytes, formatRate, parseServerDate } = useFormatters();
const { config } = useAppConfig();

const clients = ref([]);
const loading = ref(true);
const lastUpdated = ref('Updating...');
const searchQuery = ref('');
const hideDisconnected = ref(false);
const currentSort = ref('sent');
const historyModal = ref(null);

let intervalId = null;

const stats = computed(() => {
  let totalReceived = 0;
  let totalSent = 0;
  let activeClients = 0;

  clients.value.forEach(c => {
    totalReceived += c.total_bytes_received || 0;
    totalSent += c.total_bytes_sent || 0;
    if (c.status === 'Active') activeClients++;
  });

  return { totalReceived, totalSent, activeClients };
});

const filteredClients = computed(() => {
  return clients.value.filter(c => {
    if (hideDisconnected.value && c.status !== 'Active') return false;
    if (searchQuery.value && !c.common_name.toLowerCase().includes(searchQuery.value.toLowerCase().trim())) return false;
    return true;
  }).sort((a, b) => {
    if (a.status === 'Active' && b.status !== 'Active') return -1;
    if (a.status !== 'Active' && b.status === 'Active') return 1;
    const valA = currentSort.value === 'received' ? a.total_bytes_received : a.total_bytes_sent;
    const valB = currentSort.value === 'received' ? b.total_bytes_received : b.total_bytes_sent;
    return valB - valA;
  });
});

// Group for the divider headers
const groupedClients = computed(() => {
  const groups = [];
  let currentStatus = null;
  let currentGroup = null;

  filteredClients.value.forEach(c => {
    if (c.status !== currentStatus) {
      currentStatus = c.status;
      currentGroup = { status: c.status, items: [] };
      groups.push(currentGroup);
    }
    currentGroup.items.push(c);
  });
  return groups;
});

const loadData = async () => {
  try {
    const res = await fetchStats();
    if (res.success) {
      clients.value = res.data;
      lastUpdated.value = new Date().toLocaleTimeString();
    }
  } catch (e) {
    console.error(e);
  } finally {
    loading.value = false;
  }
};

const formatDate = (dateStr) => {
    if (!dateStr || dateStr === 'N/A') return 'N/A';
    const d = parseServerDate(dateStr);
    return !isNaN(d) ? d.toLocaleString() : dateStr;
};

const openHistory = (name) => {
  historyModal.value.open(name);
};

onMounted(() => {
  loadData();
  const refreshTime = config.value?.refresh_interval || 30000;
  intervalId = setInterval(loadData, refreshTime);
});

onUnmounted(() => {
  if (intervalId) clearInterval(intervalId);
});
</script>

<style scoped>
.cursor-pointer {
    cursor: pointer;
}
</style>
