<template>
  <template v-if="visible">
    <v-sheet elevation="4" width="96vw" rounded="lg" class="mt-3">
      <v-expansion-panels>
        <v-expansion-panel>
          <v-expansion-panel-title>
            <div class="d-flex justify-content-between align-items-center">
              <div class="mr-3" v-if="sensorData?.voltage">
                Name: {{ node.id }} (Status: online)
              </div>
              <div class="mr-3" v-else>
                Name: {{ node.id }} (Status: offline)
              </div>
            </div>
          </v-expansion-panel-title>

          <v-expansion-panel-text>
            <div class="d-flex flex-column">
              <div class="d-flex align-items-center mb-2">
                <span class="mr-2">Coordinates:</span>
                <span>La: {{ node.coord_la }}, Long: {{ node.coord_lo }}</span>
              </div>
              <div class="d-flex align-items-center mb-2">
                <span class="mr-2">Temperature:</span>
                <span>{{ sensorData?.temperature !== undefined ? sensorData.temperature : 'NaN' }}°C</span>
              </div>
              <div class="d-flex align-items-center mb-2">
                <span class="mr-2">Battery Voltage:</span>
                <span>{{ sensorData?.voltage || 'N/A' }}V</span>
              </div>
              <div class="d-flex align-items-center mb-2">
                <span class="mr-2">Runtime:</span>
                <span>{{ sensorData?.uptime ? (sensorData.uptime / 3600).toFixed(2) + ' hours' : 'N/A' }}</span>
              </div>
            </div>
          </v-expansion-panel-text>
        </v-expansion-panel>
      </v-expansion-panels>
    </v-sheet>
  </template>
</template>

<script setup lang="ts">
import { Node, SensorData } from "@/types"; 
import { ComputedRef, inject, ref, watch, onMounted } from "vue";
import { key } from "@/store";
import axios from "axios";

const props = defineProps<{ node: Node }>();
const visible = ref(true);
const sensorData = ref<SensorData | null>(null);

const { searching, visibleIds } = inject(key) as {
  searching: ComputedRef<boolean>;
  visibleIds: ComputedRef<string[]>;
};

watch([searching, visibleIds], ([searching, visibleIds]) => {
  visible.value = searching ? visibleIds.includes(props.node.id) : true;
});

onMounted(async () => {
  try {
    const { data } = await axios.get<SensorData>(
      `http://localhost:8080/api/v1/data?id=${props.node.id}`
    );
    sensorData.value = data;
  } catch (error) {
    console.error("Error fetching sensor data:", error);
  }
});
