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

interface CountryItem {
    name: string
    code: string
    past: number
    upcoming: number
}

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

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

const countries = computed(() => props.flightStats.countries.value.countries)

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

<template>
    <ScrollingHorizontalBarChart
        title="Top countries"
        :series="flightStats.countries.value.series"
        :categories="countries.map(c => c.name)"
        :footer-value="countries.length"
        footer-label="total countries"
        :max-visible="18"
        :events="chartEvents"
        @mousemove="onMouseMove"
        @mouseleave="onMouseLeave"
    >
        <template #tooltip="{ visible, x, y, index }">
            <ChartTooltip :visible="visible" :x="x" :y="y">
                <div class="ct-name">
                    <span v-if="index !== null" :class="`fi fi-${countries[index].code.toLowerCase()}`" />
                    {{ index !== null ? countries[index].name : '' }}
                </div>
                <div class="ct-row">
                    <span class="ct-label">Flights</span>
                    <span class="ct-val">{{ index !== null ? countries[index].past : '' }}</span>
                </div>
                <div v-if="index !== null && countries[index].upcoming" class="ct-row">
                    <span class="ct-label">Upcoming</span>
                    <span class="ct-val">{{ countries[index].upcoming }}</span>
                </div>
            </ChartTooltip>
        </template>
    </ScrollingHorizontalBarChart>
</template>
