

<script setup lang="ts">
import { ref, computed, onMounted, nextTick } from 'vue'
import { useRoute } from 'vue-router'
import { store } from '../store'
import { get_request } from '../ajax_requests'
import { ALARMS_ENDPOINT, CELLSITES_ENDPOINT, INCIDENTS_ENDPOINT, ROBOTS_ENDPOINT } from '../main'

import Nav from '../components/Nav.vue'
import Map from '../components/Map.vue'
import AlarmsCard from '../components/AlarmsCard.vue'
import IncidentCard from '../components/IncidentCard.vue'

import { use_timeline } from '../composables/use_timeline'
import { use_filtered_data } from '../composables/use_filtered_data'
import TimelineRow from '../components/TimelineRow.vue'
import FilterRow from '../components/FilterRow.vue'

const active_tab = computed({
    get: () => (store.detail_tabs[`cellsite_${id}`] ?? 'alarms') as 'alarms' | 'incidents',
    set: (val) => { store.detail_tabs[`cellsite_${id}`] = val }
})

const route = useRoute()
const loading = ref(true)
const id = Number(route.params.id)

// FIXME: Hardcoding stat fields for now. They probably won't change from opencellid
const stats_fields = computed(() => [
    ['RADIO',   site.value?.radio],
    ['MCC',     site.value?.mcc],
    ['NET',     site.value?.net],
    ['AREA',    site.value?.area],
    ['CELL',    site.value?.cell],
    ['UNIT',    site.value?.unit],
    ['LAT',     site.value?.lat],
    ['LON',     site.value?.lon],
    ['RANGE',   site.value?.range],
    ['SAMPLES', site.value?.samples],
    ['SIGNAL',  site.value?.averageSignal],
    ['CREATED', site.value?.created],
    ['UPDATED', site.value?.updated],
])

const site = computed(() =>
  store.cellsites.find(s => s.id === id)
)

const fetch_all = async (before?: number) => {
    const was_live = store.is_live
    const alarm_url = before ? `${ALARMS_ENDPOINT}?id=${id}&before=${before}` : `${ALARMS_ENDPOINT}?id=${id}`
    const incident_url = before ? `${INCIDENTS_ENDPOINT}?id=${id}&before=${before}` : `${INCIDENTS_ENDPOINT}?id=${id}`
    const [alarms, incidents, robots] = await Promise.all([
        get_request(alarm_url),
        get_request(incident_url),
        get_request(ROBOTS_ENDPOINT),
    ])
    store.set_alarms(alarms)
    store.set_incidents(incidents)
    store.set_robots(robots)
    if (before === undefined && !store.is_frozen && was_live) {
        const now = Date.now()
        store.timeline_max = now
        store.timeline_position = now
    } else {
        store.timeline_max = Date.now()
    }
}

const { timeline_position_debounced, is_live_debounced, manual_refresh, freeze, snap_to_live } = use_timeline(fetch_all)
const { visible_alarms, visible_incidents, filtered_alarms, filtered_incidents } = use_filtered_data(is_live_debounced, timeline_position_debounced)

onMounted(async () => {
  console.log(store.is_live)
    const site_exists = store.cellsites.some(s => s.id === id)
    if (!site_exists) {
        const data = await get_request(`${CELLSITES_ENDPOINT}/${id}`)
        store.set_cellsites(data)
    }
    // Incase you refresh or nav to the page directly.
    try {
        await fetch_all()
        const all = [...store.alarms, ...store.incidents]
        if (all.length > 0) {
            const oldest = Math.min(...all.map(r => new Date(r.created + ' UTC').getTime()))
            store.timeline_min = store.timeline_min === 0 ? oldest : Math.min(store.timeline_min, oldest)
        } else if (store.timeline_min === 0) {
            store.timeline_min = Date.now() - 86400000
        }
    } catch (error) {
        console.error('Error fetching data:', error)
    } finally {
        loading.value = false
    }
})
</script>

<template>
  <div :class="{ mode_historical: store.is_historical && !store.is_frozen, mode_frozen: store.is_frozen }">
    <Nav />
    <div class="site_container">

      <div v-if="loading" class="loading-overlay">
        <p>Loading...</p>
      </div>

      <div v-else-if="!site" class="not-found">
        <p>Not found</p>
      </div>

      <div v-else class="site_content">
        <div class="stats">
          <div class="site_id">SITE {{ site.id }}</div>
          <div class="stat_row" v-for="[key, val] in stats_fields" :key="key">
            <span class="stat_key">{{ key }}</span>
            <span class="stat_val">{{ val }}</span>
          </div>
        </div>

        <!-- FIXME: Map container leftover from previous version. Map can take height props. Refactor this. -->
        <div class="map_container content_frame">
        <Map
          v-if="site.lat != null && site.lon != null"
          :center="[site.lat, site.lon]"
          :zoom="12"
          :site_id="site.id"
          :robots="store.robots"
        />
        </div>

        <div class="data">
          <div class="tabs">
            <button class="tab_btn" :class="{ active: active_tab === 'alarms' }" @click="active_tab = 'alarms'">
              Alarms <span class="tab_count">{{ filtered_alarms.length }}</span>
            </button>
            <button class="tab_btn" :class="{ active: active_tab === 'incidents' }" @click="active_tab = 'incidents'">
              Incidents <span class="tab_count">{{ filtered_incidents.length }}</span>
            </button>
          </div>
          <div class="data_scroll">
            <AlarmsCard v-if="active_tab === 'alarms' && filtered_alarms.length > 0" :data="filtered_alarms" />
            <p v-else-if="active_tab === 'alarms'">All quiet here... too quiet...</p>

            <IncidentCard v-if="active_tab === 'incidents'" :data="filtered_incidents" />
          </div>
        </div>
      </div>
      
      <FilterRow
          :count="active_tab === 'incidents' ? filtered_incidents.length : filtered_alarms.length"
          :label="active_tab === 'incidents' ? 'tickets' : 'alarms'"
      />
      <TimelineRow @refresh="manual_refresh" @freeze="freeze" @snap_to_live="snap_to_live" />
    </div>
  </div>
</template>


<style scoped>
.site_container {
  position: relative;
  padding: 1rem;
}

.site_content {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-template-rows: auto auto;
  grid-template-areas:
    "stats map"
    "data data";
  gap: 1rem;
  align-items: start;
}

.site_id {
    font-size: 1.4rem;
    color: var(--theme, rgba(255, 100, 0, 1));
    margin-bottom: 1rem;
    letter-spacing: 0.05em;
}

.stat_row {
    display: flex;
    justify-content: space-between;
    padding: 0.3rem 0;
    border-bottom: 1px solid var(--theme-faint);
    font-size: 0.8rem;
}

.stat_key {
    color: var(--theme-dim); 
}

.stat_val {
    color: rgba(255, 255, 255, 0.8);
}

.stats {
  grid-area: stats;
}

.map_container {
  grid-area: map;
  min-height: 400px;
}

.data {
  grid-area: data;
  margin-top: 1rem;
}

.tabs {
  margin-bottom: 1rem;
}

.loading-overlay,
.not-found {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background: rgba(10, 10, 10, 0.95);
  z-index: 10;
  font-size: 1.5rem;
  text-align: center;
  color: rgba(255, 100, 0, 0.8);
}

@media (max-width: 768px) {
  .site_content {
    grid-template-columns: 1fr;
    grid-template-areas:
      "stats"
      "map"
      "data";
  }

  .map_container {
    height: 300px;
  }
}
</style>
