<template>
  <div class="space-y-6">
    <div class="flex items-center justify-between">
      <h1 class="text-3xl font-bold text-white">Dashboard</h1>
      <div class="flex items-center gap-2">
        <div
          class="w-3 h-3 rounded-full"
          :class="isConnected ? 'bg-green-400 animate-pulse' : 'bg-red-400'"
        ></div>
        <span class="text-sm text-white/70">
          {{ isConnected ? 'Live' : 'Disconnected' }}
        </span>
      </div>
    </div>

    <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
      <GlassCard class="p-6">
        <div class="flex items-center justify-between mb-2">
          <p class="text-white/50 text-sm">Total Peers</p>
          <svg class="w-5 h-5 text-cyan-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z" />
          </svg>
        </div>
        <p class="text-3xl font-bold text-white">{{ stats.totalPeers }}</p>
      </GlassCard>

      <GlassCard class="p-6">
        <div class="flex items-center justify-between mb-2">
          <p class="text-white/50 text-sm">Active Peers</p>
          <svg class="w-5 h-5 text-green-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
          </svg>
        </div>
        <p class="text-3xl font-bold text-green-400">{{ stats.activePeers }}</p>
      </GlassCard>

      <GlassCard class="p-6">
        <div class="flex items-center justify-between mb-2">
          <p class="text-white/50 text-sm">Active Rules</p>
          <svg class="w-5 h-5 text-purple-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z" />
          </svg>
        </div>
        <p class="text-3xl font-bold text-purple-400">{{ stats.totalRules }}</p>
      </GlassCard>
    </div>

    <GlassCard class="p-6">
      <h2 class="text-xl font-semibold text-cyan-400 mb-4">Traffic Overview</h2>
      <div class="h-64">
        <Line v-if="chartData.datasets[0].data.length > 0" :data="chartData" :options="chartOptions" />
        <div v-else class="flex items-center justify-center h-full text-white/30">
          Waiting for data...
        </div>
      </div>
    </GlassCard>

    <GlassCard class="p-6">
      <h2 class="text-xl font-semibold text-cyan-400 mb-4">Peer Status</h2>
      <div v-if="stats.peers.length > 0" class="space-y-2 max-h-64 overflow-y-auto">
        <div
          v-for="peer in stats.peers"
          :key="peer.publicKey"
          class="flex items-center justify-between p-3 bg-white/5 rounded-lg"
        >
          <div class="flex items-center gap-3">
            <div
              class="w-2 h-2 rounded-full"
              :class="peer.isOnline ? 'bg-green-400' : 'bg-gray-500'"
            ></div>
            <span class="text-white font-mono text-sm">{{ peer.ip }}</span>
          </div>
          <div class="text-white/50 text-xs">
            RX: {{ formatBytes(peer.rxBytes) }} | TX: {{ formatBytes(peer.txBytes) }}
          </div>
        </div>
      </div>
      <p v-else class="text-white/30">No peer data available</p>
    </GlassCard>

    <div v-if="error" class="p-4 bg-red-500/20 border border-red-500/50 rounded-lg text-red-400">
      {{ error }}
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted } from 'vue'
import { Line } from 'vue-chartjs'
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Title,
  Tooltip,
  Legend,
  Filler
} from 'chart.js'
import GlassCard from '../components/glass/GlassCard.vue'
import { useWebSocket } from '../composables/useWebSocket'

ChartJS.register(
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Title,
  Tooltip,
  Legend,
  Filler
)

const { isConnected, stats, error, connect } = useWebSocket('ws://localhost:8080/ws/stats')

onMounted(() => {
  connect()
})

const chartData = computed(() => {
  const history = stats.value.trafficHistory || []
  return {
    labels: history.map((_, i) => `${i}s`),
    datasets: [
      {
        label: 'Download (RX)',
        data: history.map(p => p.rxBytes),
        borderColor: 'rgb(34, 211, 238)',
        backgroundColor: 'rgba(34, 211, 238, 0.1)',
        fill: true,
        tension: 0.4
      },
      {
        label: 'Upload (TX)',
        data: history.map(p => p.txBytes),
        borderColor: 'rgb(168, 85, 247)',
        backgroundColor: 'rgba(168, 85, 247, 0.1)',
        fill: true,
        tension: 0.4
      }
    ]
  }
})

const chartOptions = {
  responsive: true,
  maintainAspectRatio: false,
  plugins: {
    legend: {
      labels: {
        color: 'rgba(255, 255, 255, 0.7)'
      }
    },
    tooltip: {
      backgroundColor: 'rgba(0, 0, 0, 0.8)',
      titleColor: '#fff',
      bodyColor: '#fff',
      callbacks: {
        label: (context: any) => {
          return `${context.dataset.label}: ${formatBytes(context.parsed.y)}`
        }
      }
    }
  },
  scales: {
    x: {
      ticks: { color: 'rgba(255, 255, 255, 0.5)' },
      grid: { color: 'rgba(255, 255, 255, 0.1)' }
    },
    y: {
      ticks: {
        color: 'rgba(255, 255, 255, 0.5)',
        callback: (value: number) => formatBytes(value)
      },
      grid: { color: 'rgba(255, 255, 255, 0.1)' }
    }
  }
}

function formatBytes(bytes: number): string {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}
</script>
