<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 AircraftItem {
    label: string
    id: number
    past: number
    upcoming: number
    designator: string
}

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

const { tooltipItem, onMouseMove, onMouseLeave } = useChartTooltip<AircraftItem>()

const aircraft = computed(() => props.flightStats.topAircraft.value.aircraft)

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

<template>
    <ScrollingHorizontalBarChart
        title="Top aircraft"
        :series="flightStats.topAircraft.value.series"
        :categories="aircraft.map(a => a.label)"
        :footer-value="aircraft.length"
        footer-label="total aircraft"
        :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 ? aircraft[index].label : '' }}
                </div>
                <div class="ct-row">
                    <InlineBadge v-if="index !== null" variant="generic">{{ aircraft[index].designator }}</InlineBadge>
                </div>
                <div class="ct-row">
                    <span class="ct-label">Flights</span>
                    <span class="ct-val">{{ index !== null ? aircraft[index].past : '' }}</span>
                </div>
                <div v-if="index !== null && aircraft[index].upcoming" class="ct-row">
                    <span class="ct-label">Upcoming</span>
                    <span class="ct-val">{{ aircraft[index].upcoming }}</span>
                </div>
            </ChartTooltip>
        </template>
    </ScrollingHorizontalBarChart>
</template>
