<template>
  <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 pb-20">
    <div class="space-y-6">
      <div class="grid grid-cols-2 sm:grid-cols-3 gap-4">
        <MetricCard title="Current Energy" :content="currentEnergyValue" details="kWh" />
        <MetricCard title="Average Usage" :content="averageEnergyUsage" details="kWh" />
        <MetricCard
          title="Connection Status"
          :content="websocketStore.isConnected ? 'Connected' : 'Disconnected'"
        />
        <GraphMetricCard
          title="Real-time Energy"
          :content="currentEnergyValue"
          details="kWh"
          :trend-data="energyStore.energyHistory.slice(-8)"
          trend-direction="neutral"
        />
        <GraphMetricCard title="Average CO2" :content="averageCO2" details="ppm" />
        <GraphMetricCard title="Max CO2" :content="maxCO2" details="ppm" />
      </div>
      <SensorConsumptionTable />
    </div>

    <div class="space-y-6">
      <RealtimeEnergyChartCard title="Month" />
      <RoomMetricsCard />
      <AirQualityCard />
    </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 RoomMetricsCard from '@/components/cards/RoomMetricsCard.vue'
import AirQualityCard from '@/components/cards/AirQualityCard.vue'
import { useEnergyStore } from '@/stores/energy'
import { useSensorStore } from '@/stores/sensor'
import { useSettingsStore } from '@/stores/settings'
import { computed, onMounted, onUnmounted } from 'vue'
import { useWebSocketStore } from '@/stores/websocket'

const energyStore = useEnergyStore()
const sensorStore = useSensorStore()
const websocketStore = useWebSocketStore()
const settingsStore = useSettingsStore()

const currentEnergyValue = computed(() => {
  return energyStore.currentEnergyValue.toFixed(2)
})

const averageEnergyUsage = computed(() => {
  return energyStore.averageEnergyUsage.toFixed(2)
})

const averageCO2 = computed(() => {
  return Math.round(sensorStore.averageCO2Level)
})

const maxCO2 = computed(() => {
  return Math.round(sensorStore.maxCO2Level)
})

onMounted(() => {
  settingsStore.initialize()

  if (settingsStore.settings.autoConnect) {
    websocketStore.connect(settingsStore.settings.websocketUrl)
  }
})

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