<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'
import ServiceTabLayout from '@/Components/Panel/ServiceTabLayout.vue'
import type { Service } from '@/types'

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

interface ResourceEntry {
  timestamp: string
  value: number
}

interface ResourceData {
  cpu: ResourceEntry[]
  memory: ResourceEntry[]
  disk: ResourceEntry[]
  network: ResourceEntry[]
}

interface Props {
  service: Service
  resourceData: ResourceData
}

const props = defineProps<Props>()

const period = ref<string>('24h')

const tabs = computed(() => [
  { label: 'Dashboard', icon: 'tabler-dashboard', to: `/services/${props.service.id}/vps-panel` },
  { label: 'Console', icon: 'tabler-terminal-2', to: `/services/${props.service.id}/vps-panel/console` },
  { label: 'Graphs', icon: 'tabler-chart-line', to: `/services/${props.service.id}/vps-panel/graphs` },
  { label: 'Firewall', icon: 'tabler-shield', to: `/services/${props.service.id}/vps-panel/firewall` },
  { label: 'Snapshots', icon: 'tabler-camera', to: `/services/${props.service.id}/vps-panel/snapshots` },
  { label: 'Backups', icon: 'tabler-database', to: `/services/${props.service.id}/vps-panel/backups` },
  { label: 'Network', icon: 'tabler-network', to: `/services/${props.service.id}/vps-panel/network` },
  { label: 'Rebuild', icon: 'tabler-reload', to: `/services/${props.service.id}/vps-panel/rebuild` },
  { label: 'Settings', icon: 'tabler-settings', to: `/services/${props.service.id}/vps-panel/settings` },
  { label: 'Activity', icon: 'tabler-history', to: `/services/${props.service.id}/vps-panel/activity` },
])

function makeChartOption(label: string, color: string, data: ResourceEntry[], unit: string): Record<string, unknown> {
  return {
    tooltip: {
      trigger: 'axis',
      formatter: (params: Array<{ value: number; axisValueLabel: string }>) => {
        return `${params[0]?.axisValueLabel ?? ''}<br/>${label}: ${params[0]?.value ?? 0}${unit}`
      },
    },
    grid: { left: '3%', right: '3%', bottom: '8%', top: '8%', containLabel: true },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: data.map(d => d.timestamp),
    },
    yAxis: { type: 'value', max: unit === '%' ? 100 : undefined },
    series: [{
      type: 'line',
      smooth: true,
      symbol: 'none',
      areaStyle: { opacity: 0.15, color },
      lineStyle: { color, width: 2 },
      itemStyle: { color },
      data: data.map(d => d.value),
    }],
  }
}

const hasData = computed<boolean>(() => {
  return (
    props.resourceData.cpu.length > 0 ||
    props.resourceData.memory.length > 0 ||
    props.resourceData.disk.length > 0 ||
    props.resourceData.network.length > 0
  )
})
</script>

<template>
  <ServiceTabLayout
    :service="service"
    :tabs="tabs"
    :current-tab="`/services/${service.id}/vps-panel/graphs`"
  >
    <div class="d-flex align-center justify-space-between mb-6">
      <h3 class="text-h5 font-weight-bold">
        <VIcon icon="tabler-chart-line" class="me-2" color="primary" />
        Resource Graphs
      </h3>
      <VBtnToggle v-model="period" mandatory variant="outlined" divided>
        <VBtn value="1h" size="small">1H</VBtn>
        <VBtn value="24h" size="small">24H</VBtn>
        <VBtn value="7d" size="small">7D</VBtn>
        <VBtn value="30d" size="small">30D</VBtn>
      </VBtnToggle>
    </div>

    <VAlert
      v-if="!hasData"
      type="info"
      variant="tonal"
      class="mb-6"
    >
      Resource graphs require API configuration. Connect VirtFusion to see live metrics.
    </VAlert>

    <VRow>
      <VCol cols="12" md="6">
        <VCard elevation="0" class="mb-6">
          <VCardTitle class="text-body-1 font-weight-bold">
            <VIcon icon="tabler-cpu" color="info" class="me-2" />
            CPU Usage
          </VCardTitle>
          <VCardText>
            <VChart
              v-if="resourceData.cpu.length > 0"
              :option="makeChartOption('CPU', '#3b82f6', resourceData.cpu, '%')"
              autoresize
              style="height: 250px;"
            />
            <div v-else class="text-center text-medium-emphasis pa-8">
              No CPU data available
            </div>
          </VCardText>
        </VCard>
      </VCol>

      <VCol cols="12" md="6">
        <VCard elevation="0" class="mb-6">
          <VCardTitle class="text-body-1 font-weight-bold">
            <VIcon icon="tabler-cpu-2" color="success" class="me-2" />
            Memory Usage
          </VCardTitle>
          <VCardText>
            <VChart
              v-if="resourceData.memory.length > 0"
              :option="makeChartOption('Memory', '#10b981', resourceData.memory, '%')"
              autoresize
              style="height: 250px;"
            />
            <div v-else class="text-center text-medium-emphasis pa-8">
              No memory data available
            </div>
          </VCardText>
        </VCard>
      </VCol>

      <VCol cols="12" md="6">
        <VCard elevation="0" class="mb-6">
          <VCardTitle class="text-body-1 font-weight-bold">
            <VIcon icon="tabler-database" color="warning" class="me-2" />
            Disk Usage
          </VCardTitle>
          <VCardText>
            <VChart
              v-if="resourceData.disk.length > 0"
              :option="makeChartOption('Disk', '#f59e0b', resourceData.disk, '%')"
              autoresize
              style="height: 250px;"
            />
            <div v-else class="text-center text-medium-emphasis pa-8">
              No disk data available
            </div>
          </VCardText>
        </VCard>
      </VCol>

      <VCol cols="12" md="6">
        <VCard elevation="0" class="mb-6">
          <VCardTitle class="text-body-1 font-weight-bold">
            <VIcon icon="tabler-network" color="error" class="me-2" />
            Network I/O
          </VCardTitle>
          <VCardText>
            <VChart
              v-if="resourceData.network.length > 0"
              :option="makeChartOption('Network', '#ef4444', resourceData.network, ' MB/s')"
              autoresize
              style="height: 250px;"
            />
            <div v-else class="text-center text-medium-emphasis pa-8">
              No network data available
            </div>
          </VCardText>
        </VCard>
      </VCol>
    </VRow>
  </ServiceTabLayout>
</template>
