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

interface AirlineItem {
    name: string
    past: number
    upcoming: number
    id: number
    logo_url: string
}

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

const page = usePage<SharedProps>().props
const { tooltipItem, tooltipX, tooltipY, onMouseMove, onMouseLeave } = useChartTooltip<AirlineItem>()

const airlines = computed(() => props.flightStats.topAirlines.value.airlines)

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

<template>
    <ScrollingHorizontalBarChart
        title="Top airlines"
        :series="flightStats.topAirlines.value.series"
        :categories="airlines.map(a => a.name)"
        :footer-value="airlines.length"
        footer-label="total airlines"
        :limit="12"
        :events="chartEvents"
        @mousemove="onMouseMove"
        @mouseleave="onMouseLeave"
    >
        <template #tooltip="{ visible, x, y, index }">
            <ChartTooltip :visible="visible" :x="x" :y="y">
                <div class="ct-name">
                    <img :src="`${index !== null ? airlines[index].logo_url : ''}`" width="24" height="24"/>
                    {{ index !== null ? airlines[index].name : '' }}
                </div>
                <div class="ct-row">
                    <span class="ct-label">Flights</span>
                    <span class="ct-val">{{ index !== null ? airlines[index].past : '' }}</span>
                </div>
                <div v-if="index !== null && airlines[index].upcoming" class="ct-row">
                    <span class="ct-label">Upcoming</span>
                    <span class="ct-val">{{ airlines[index].upcoming }}</span>
                </div>
            </ChartTooltip>
        </template>
    </ScrollingHorizontalBarChart>
</template>
