<script lang="ts" setup>
import { computed, ref } from 'vue'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
} from 'echarts/components'
import VChart from 'vue-echarts'

use([CanvasRenderer, LineChart, TitleComponent, TooltipComponent, GridComponent, LegendComponent])

interface BandwidthEntry {
  date: string
  in: number
  out: number
}

interface Props {
  data: BandwidthEntry[]
  period?: string
}

const props = withDefaults(defineProps<Props>(), {
  period: '24h',
})

function formatBytes(bytes: number): string {
  if (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 chartOption = computed(() => ({
  tooltip: {
    trigger: 'axis',
    formatter: (params: Array<{ seriesName: string; value: number; axisValueLabel: string }>) => {
      let html = `<div style="font-weight:600;margin-bottom:4px;">${params[0]?.axisValueLabel ?? ''}</div>`
      params.forEach((p) => {
        const color = p.seriesName === 'Inbound' ? '#3b82f6' : '#10b981'
        html += `<div style="display:flex;align-items:center;gap:6px;"><span style="width:8px;height:8px;border-radius:50%;background:${color};display:inline-block;"></span>${p.seriesName}: ${formatBytes(p.value)}</div>`
      })
      return html
    },
  },
  legend: {
    data: ['Inbound', 'Outbound'],
    bottom: 0,
  },
  grid: {
    left: '3%',
    right: '3%',
    bottom: '12%',
    top: '8%',
    containLabel: true,
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: props.data.map(d => d.date),
  },
  yAxis: {
    type: 'value',
    axisLabel: {
      formatter: (val: number) => formatBytes(val),
    },
  },
  series: [
    {
      name: 'Inbound',
      type: 'line',
      smooth: true,
      symbol: 'none',
      areaStyle: { opacity: 0.15, color: '#3b82f6' },
      lineStyle: { color: '#3b82f6', width: 2 },
      itemStyle: { color: '#3b82f6' },
      data: props.data.map(d => d.in),
    },
    {
      name: 'Outbound',
      type: 'line',
      smooth: true,
      symbol: 'none',
      areaStyle: { opacity: 0.15, color: '#10b981' },
      lineStyle: { color: '#10b981', width: 2 },
      itemStyle: { color: '#10b981' },
      data: props.data.map(d => d.out),
    },
  ],
}))
</script>

<template>
  <div class="bandwidth-chart">
    <VChart
      v-if="data.length > 0"
      :option="chartOption"
      autoresize
      style="height: 300px; width: 100%;"
    />
    <div v-else class="text-center text-medium-emphasis pa-8">
      <VIcon icon="tabler-chart-line" size="48" class="mb-2" />
      <div class="text-body-1">No bandwidth data available for this period</div>
    </div>
  </div>
</template>
