<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
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 Table from '../components/Table.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'

// TODO: Add search, sort, filter on alarms + sites

const loading = ref(true)

const active_tab = computed({
    get: () => (store.detail_tabs['home'] ?? 'map') as 'map' | 'alarms' | 'incidents' | 'sites' | 'robots',
    set: (val) => { store.detail_tabs['home'] = val }
})

// const severity_filter = ref<number | null>(null) // NOTE: Null here means show all severities.
const status_filter = ref<string | null>(null)

const displayed_incidents = computed(() => {
    if (status_filter.value === null) return filtered_incidents.value
    return filtered_incidents.value.filter(i => i.status === status_filter.value)
})

const fetch_all = async (before?: number) => {
    const was_live = store.is_live
    const alarm_url = before ? `${ALARMS_ENDPOINT}?before=${before}` : `${ALARMS_ENDPOINT}`
    const incident_url = before ? `${INCIDENTS_ENDPOINT}?before=${before}` : `${INCIDENTS_ENDPOINT}`
    const robot_url = `${ROBOTS_ENDPOINT}`
    const [alarms, incidents, robots] = await Promise.all([
        get_request(alarm_url),
        get_request(incident_url),
        get_request(robot_url),
    ])
    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 () => {
    // store.unfreeze() // TODO: EXPERIMENT: My current idea is that FREEZING should freeze the entire app. So a user can investigate at a point in time throughout. A full page reload will reset this.

    try {
        const [sites, robots] = await Promise.all([
            get_request(`${CELLSITES_ENDPOINT}`),
            get_request(`${ROBOTS_ENDPOINT}`),
        ])
        store.set_cellsites(sites)
        store.set_robots(robots)

        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 on initial load:', error)
    } finally {
        loading.value = false
    }
})
</script>

<template>
<div :class="{ mode_historical: store.is_historical && !store.is_frozen, mode_frozen: store.is_frozen }">
    <Nav />
    <div v-if="loading">
        <p>loading...</p>
    </div>
    <div v-else>
        <div class="tabs">
            <button 
                @click="active_tab = 'map'" 
                :class="{ active: active_tab === 'map' }"
                class="tab_btn"
            >Map
            </button>
            <button 
                @click="active_tab = 'alarms'" 
                :class="{ active: active_tab === 'alarms' }"
                class="tab_btn"
            >Alarms
            </button>
            <button 
                @click="active_tab = 'incidents'" 
                :class="{ active: active_tab === 'incidents' }"
                class="tab_btn"
                >Incident Tickets
            </button>
            <button 
                @click="active_tab = 'sites'" 
                :class="{ active: active_tab === 'sites' }"
                class="tab_btn"
            >Sites
            </button>
            <button
                @click="active_tab = 'robots'"
                :class="{ active: active_tab === 'robots' }"
                class="tab_btn"
            >Robots
            </button>
        </div>
        <div class="content_frame">
            <div v-if="active_tab === 'map'">
                <Map :alarms="filtered_alarms" :robots="store.robots" map_height="80vh" />
            </div>
            <div v-if="active_tab === 'alarms'">
                <div class="alarm_scroll">
                    <AlarmsCard v-if="filtered_alarms.length > 0" :data="filtered_alarms" />
                    <p v-else>All quiet in here... too quiet...</p>
                </div>
            </div>
            <div v-if="active_tab === 'incidents'">
                <div class="alarm_toolbar">
                    <div class="severity_filters">
                        <button class="tab_btn" :class="{ active: status_filter === null }" @click="status_filter = null">ALL</button>
                        <button class="tab_btn" :class="{ active: status_filter === 'active' }" @click="status_filter = 'active'">ACTIVE</button>
                        <button class="tab_btn" :class="{ active: status_filter === 'closed' }" @click="status_filter = 'closed'">CLOSED</button>
                    </div>
                </div>
                <div class="alarm_scroll">
                    <IncidentCard :data="displayed_incidents" />
                </div>
            </div>
            <div v-if="active_tab === 'sites'">
                <div class="alarm_scroll">
                    <Table :data="store.cellsites" link_prefix="/cellsites" />
                </div>
            </div>
            <div v-if="active_tab === 'robots'">
                <div class="alarm_scroll">
                    <Table :data="store.robots" link_prefix="/robots" />
                </div>
            </div>
            <FilterRow
                :count="active_tab === 'incidents' ? filtered_incidents.length : active_tab === 'robots' ? store.robots.length : filtered_alarms.length"
                :label="active_tab === 'incidents' ? 'tickets' : active_tab === 'robots' ? 'robots' : 'alarms'"
            />
            <TimelineRow @refresh="manual_refresh" @freeze="freeze" @snap_to_live="snap_to_live" />
        </div>

    </div>
</div>
</template>

<style scoped>
#map, .tabs {
    margin-bottom: 2rem;
}

.alarm_toolbar {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 1rem;
}

.alarm_scroll {
    height: 60vh;
    overflow-y: auto;
}

</style>