<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"
import InlineBadge from "@/Components/FlightsGoneBy/InlineBadge.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"
        :limit="12"
    >
        <template #tooltip="{ visible, x, y, index }">
            <ChartTooltip :visible="visible" :x="x" :y="y">
                <div class="ct-name">{{ index !== null ? airports[index].fullName : '' }}</div>
                <div class="ct-sub"><InlineBadge variant="generic">{{ index !== null ? airports[index].label : '' }}</InlineBadge></div>
                <div class="ct-row">
                    <span class="ct-label">Departures</span>
                    <span class="ct-val">{{ index !== null ? airports[index].departures : '' }}</span>
                </div>
                <div class="ct-row">
                    <span class="ct-label">Arrivals</span>
                    <span class="ct-val">{{ index !== null ? airports[index].arrivals : '' }}</span>
                </div>
                <div v-if="index !== null && airports[index].upcoming" class="ct-row">
                    <span class="ct-label">Upcoming</span>
                    <span class="ct-val">{{ airports[index].upcoming }}</span>
                </div>
            </ChartTooltip>
        </template>
    </ScrollingHorizontalBarChart>
</template>

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