<template>
    <div class="chart-wrap">
        <div class="chart-title">Top airports</div>

        <div v-if="series.length" class="chart-outer">
            <div class="chart-scroll" :style="{ height: scrollHeight }" @mousemove="onMouseMove" @mouseleave="onMouseLeave">
                <UnstyledFlightChart
                    type="bar"
                    :height="chartHeight"
                    :options="chartOptions"
                    :series="chartSeries"
                />
            </div>

            <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>

            <div class="chart-footer">
                <span class="total-count">{{ totalAirports }}</span>
                <span class="total-label">total airports</span>
            </div>
        </div>

        <div v-else class="chart-empty">No airport data available</div>
    </div>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import type { Airport, Flight } from '@/Types/types'
import { useChartTooltip } from '@/Composables/useChartTooltip'
import ChartTooltip from '@/Components/FlightsGoneBy/Charts/ChartTooltip.vue'
import UnstyledFlightChart from "@/Components/FlightsGoneBy/UnstyledFlightChart.vue";

const props = defineProps<{
    flights: Flight[]
    upcomingFlights: Flight[]
}>()

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

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

const MAX_VISIBLE = 12
const BAR_HEIGHT = 32

function airportLabel(airport: Airport | null | undefined): string | null {
    if (!airport) return null
    return airport.iata_code ?? airport.icao_code ?? airport.name ?? null
}

const series = computed((): AirportItem[] => {
    const map = new Map<string, AirportItem>()
    const empty = (): AirportItem => ({ departures: 0, arrivals: 0, upcoming: 0, label: '', fullName: '' })

    props.flights.forEach(f => {
        const depLabel = airportLabel(f.departure_airport)
        const arrLabel = airportLabel(f.arrival_airport)

        if (depLabel) {
            const e = map.get(depLabel) ?? empty()
            e.departures++
            e.label = depLabel
            e.fullName = f.departure_airport?.name ?? depLabel
            map.set(depLabel, e)
        }
        if (arrLabel) {
            const e = map.get(arrLabel) ?? empty()
            e.arrivals++
            e.label = arrLabel
            e.fullName = f.arrival_airport?.name ?? arrLabel
            map.set(arrLabel, e)
        }
    })

    props.upcomingFlights.forEach(f => {
        const depLabel = airportLabel(f.departure_airport)
        const arrLabel = airportLabel(f.arrival_airport)

        if (depLabel) {
            const e = map.get(depLabel) ?? empty()
            e.upcoming++
            e.label = depLabel
            e.fullName = f.departure_airport?.name ?? depLabel
            map.set(depLabel, e)
        }
        if (arrLabel) {
            const e = map.get(arrLabel) ?? empty()
            e.upcoming++
            e.label = arrLabel
            e.fullName = f.arrival_airport?.name ?? arrLabel
            map.set(arrLabel, e)
        }
    })

    return [...map.values()]
        .sort((a, b) =>
            (b.departures + b.arrivals + b.upcoming) - (a.departures + a.arrivals + a.upcoming)
        )
})

const totalAirports = computed(() => series.value.length)
const chartHeight = computed(() => series.value.length * BAR_HEIGHT + 40)
const scrollHeight = computed(() => {
    const visible = Math.min(series.value.length, MAX_VISIBLE)
    return `${visible * BAR_HEIGHT + 40}px`
})

const chartSeries = computed(() => [
    { name: 'Departures', data: series.value.map(s => s.departures) },
    { name: 'Arrivals',   data: series.value.map(s => s.arrivals) },
    { name: 'Upcoming',   data: series.value.map(s => s.upcoming) },
])

const chartOptions = computed(() => ({
    chart: {
        type: 'bar',
        background: 'transparent',
        fontFamily: 'inherit',
        toolbar: { show: false },
        animations: { enabled: false },
        stacked: true,
        events: {
            mouseMove: (_e: MouseEvent, _chart: unknown, config: { dataPointIndex: number }) => {
                if (config.dataPointIndex < 0) { tooltipItem.value = null; return }
                tooltipItem.value = series.value[config.dataPointIndex] ?? null
            },
            mouseLeave: () => { tooltipItem.value = null },
        },
    },
    theme: { mode: 'dark' },
    plotOptions: {
        bar: {
            horizontal: true,
            barHeight: '60%',
            borderRadius: 3,
            borderRadiusWhenStacked: 'last',
        },
    },
    colors: ['#4da6ff', '#a150d5', '#ffc107'],
    dataLabels: { enabled: false },
    xaxis: {
        categories: series.value.map(s => s.label),
        labels: { show: false },
        axisBorder: { show: false },
        axisTicks: { show: false },
    },
    yaxis: {
        labels: {
            style: { colors: '#778899', fontSize: '12px' },
        },
    },
    grid: { show: false },
    legend: {
        show: true,
        position: 'top',
        horizontalAlign: 'right',
        labels: { colors: '#778899' },
        markers: { width: 8, height: 8, radius: 2 },
        itemMargin: { horizontal: 8 },
    },
    tooltip: { enabled: false },
    states: {
        hover: { filter: { type: 'lighten', value: 0.1 } },
    },
}))
</script>

<style scoped>
.chart-wrap {
    display: flex;
    flex-direction: column;
    gap: 4px;
}

.chart-title {
    font-size: 13px;
    font-weight: 500;
    color: #556677;
    text-transform: uppercase;
    letter-spacing: 0.08em;
}

.chart-outer {
    display: flex;
    flex-direction: column;
    gap: 12px;
}

.chart-scroll {
    overflow-y: auto;
    overflow-x: hidden;
    scrollbar-width: thin;
    scrollbar-color: #334455 transparent;
}

.chart-scroll::-webkit-scrollbar { width: 4px; }
.chart-scroll::-webkit-scrollbar-track { background: transparent; }
.chart-scroll::-webkit-scrollbar-thumb { background: #334455; border-radius: 2px; }

.chart-footer {
    display: flex;
    align-items: baseline;
    gap: 6px;
    padding-left: 4px;
}

.total-count {
    font-size: 28px;
    font-weight: 600;
    color: #e0e6f0;
    line-height: 1;
}

.total-label {
    font-size: 13px;
    color: #556677;
}

.chart-empty {
    height: 280px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 13px;
    color: #445566;
}

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