<script setup lang="ts">
import { computed } from 'vue'
import { FlightStats } from "@/Composables/useFlightStats"
import { useChartTooltip } from '@/Composables/useChartTooltip'
import ScrollingHorizontalBarChart from "@/Components/FlightsGoneBy/Charts/ChartTypes/ScrollingHorizontalBarChart.vue"
import ChartTooltip from "@/Components/FlightsGoneBy/Charts/ChartTooltip.vue"

interface AirportItem {
    label: string
    fullName: string
    departures: number
    arrivals: number
    upcoming: number
}

const props = defineProps<{
    flightStats: FlightStats
}>()

const { tooltipItem, tooltipX, tooltipY, onMouseMove, onMouseLeave } = useChartTooltip<AirportItem>()

const airports = computed(() => props.flightStats.topAirports.value.airports)

const chartEvents = computed(() => ({
    mouseMove: (_e: MouseEvent, _chart: unknown, config: { dataPointIndex: number }) => {
        if (config.dataPointIndex < 0) { tooltipItem.value = null; return }
        tooltipItem.value = airports.value[config.dataPointIndex] ?? null
    },
    mouseLeave: () => { tooltipItem.value = null },
}))
</script>

<template>
    <ScrollingHorizontalBarChart
        title="Top airports"
        :series="flightStats.topAirports.value.series"
        :categories="airports.map(a => a.label)"
        :footer-value="airports.length"
        footer-label="total airports"
        :colors="['#4da6ff', '#a150d5', '#ffc107']"
        :events="chartEvents"
        @mousemove="onMouseMove"
        @mouseleave="onMouseLeave"
    >
        <template #tooltip>
            <ChartTooltip :visible="!!tooltipItem" :x="tooltipX" :y="tooltipY">
                <div class="ct-name">{{ tooltipItem?.fullName }}</div>
                <div class="ct-sub">{{ tooltipItem?.label }}</div>
                <div class="ct-row">
                    <span class="ct-label">Departures</span>
                    <span class="ct-val">{{ tooltipItem?.departures }}</span>
                </div>
                <div class="ct-row">
                    <span class="ct-label">Arrivals</span>
                    <span class="ct-val">{{ tooltipItem?.arrivals }}</span>
                </div>
                <div v-if="tooltipItem?.upcoming" class="ct-row">
                    <span class="ct-label">Upcoming</span>
                    <span class="ct-val">{{ tooltipItem?.upcoming }}</span>
                </div>
            </ChartTooltip>
        </template>
    </ScrollingHorizontalBarChart>
</template>

<style scoped>
.ct-sub {
    font-size: 11px;
    color: #556677;
    margin-bottom: 8px;
}
</style>
