<template>
  <div class="space-y-6">
    <!-- Filter Controls Row -->
    <!--div class="flex flex-col sm:flex-row gap-4 mb-6">
      <select class="px-4 py-2 border border-gray-200 rounded-lg bg-white">
        <option>Timeframe: All-time</option>
      </select>
      <select class="px-4 py-2 border border-gray-200 rounded-lg bg-white">
        <option>People: All</option>
      </select>
      <select class="px-4 py-2 border border-gray-200 rounded-lg bg-white">
        <option>Topic: All</option>
      </select>
    </div-->

    <!-- Top Metric Cards Row -->
    <div class="grid grid-cols-1 lg:grid-cols-2 gap-4 min-h-96">
      <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-x-4 gap-y-3">
        <MetricCard title="Current Energy" :content="currentEnergyValue" details="kWh" />
        <MetricCard title="Connection Status" :content="connectionStatus" />
        <MetricCard title="Average Usage" :content="averageEnergyUsage" details="kWh" />
        <GraphMetricCard
          title="Real-time Energy"
          :content="currentEnergyValue"
          details="kWh"
          :trend-data="energyStore.timeSeriesData.datasets[0].data.slice(-8)"
          trend-direction="neutral"
        />
        <GraphMetricCard
          title="Current Knowledge"
          content="86%"
          :trend-data="[203, 78, 80, 82, 142, 85, 85, 86]"
          trend-direction="down"
        />
        <GraphMetricCard
          title="Knowledge Gain"
          content="+34%"
          :trend-data="[20, 25, 28, 30, 32, 33, 34, 34]"
          trend-direction="neutral"
        />
      </div>
      <div>
        <RealtimeEnergyChartCard title="Month" />
      </div>
    </div>

    <!-- Charts and Knowledge Cards Row -->
    <div class="grid grid-cols-1 lg:grid-cols-2 gap-4">
      <SensorConsumptionTable />
    </div>
  </div>
</template>

<script setup lang="ts">
import RealtimeEnergyChartCard from '@/components/cards/RealtimeEnergyChartCard.vue'
import MetricCard from '@/components/cards/MetricCard.vue'
import GraphMetricCard from '@/components/cards/GraphMetricCard.vue'
import SensorConsumptionTable from '@/components/cards/SensorConsumptionTable.vue'
import { useEnergyStore } from '@/stores/energy'
import { computed, onMounted, onUnmounted } from 'vue'

const energyStore = useEnergyStore()

const currentEnergyValue = computed(() => {
  return energyStore.latestMessage?.value?.toFixed(2) || '0.00'
})

const connectionStatus = computed(() => {
  return energyStore.isConnected ? 'Connected' : 'Disconnected'
})

const averageEnergyUsage = computed(() => {
  const data = energyStore.timeSeriesData.datasets[0].data
  if (data.length === 0) return '0.00'
  const sum = data.reduce((acc, val) => acc + val, 0)
  return (sum / data.length).toFixed(2)
})

onMounted(() => {
  energyStore.connect('ws://192.168.1.73:8000/ws')
})

onUnmounted(() => {
  energyStore.disconnect()
})
</script>
