<script setup lang="ts">
import type { Flight } from '@/Types/types'
import { ref } from 'vue'
import { usePage } from '@inertiajs/vue3'

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

const emit = defineEmits<{
    change: [filters: {
        years: number[]
        airlines: number[]
        countries: string[]
        continents: string[]
        flightClasses: number[]
        crewTypes: number[]
    }]
}>()

// ── Available options ─────────────────────────────────────────────────────────

function buildOptions(flights: Flight[]) {
    const years      = new Set<number>()
    const airlines   = new Map<number, { id: number; name: string }>()
    const countries  = new Map<string, { code: string; name: string }>()
    const continents = new Map<string, { code: string; name: string }>()
    const classes    = new Map<number, { id: number; name: string }>()
    const crewTypes  = new Map<number, { id: number; name: string }>()

    flights.forEach(f => {
        years.add(new Date(f.departure_date).getFullYear())

        if (f.airline?.id && f.airline?.name)
            airlines.set(f.airline.id, { id: f.airline.id, name: f.airline.name })

        const dep = f.departure_airport.region
        const arr = f.arrival_airport.region

        if (dep?.country) countries.set(dep.country.code, { code: dep.country.code, name: dep.country.name })
        if (arr?.country) countries.set(arr.country.code, { code: arr.country.code, name: arr.country.name })
        if (dep?.continent) continents.set(dep.continent.code, { code: dep.continent.code, name: dep.continent.name })
        if (arr?.continent) continents.set(arr.continent.code, { code: arr.continent.code, name: arr.continent.name })

        if (f.flight_class?.id && f.flight_class?.name)
            classes.set(f.flight_class.id, { id: f.flight_class.id, name: f.flight_class.name })

        if (f.crew_type?.id && f.crew_type?.name)
            crewTypes.set(f.crew_type.id, { id: f.crew_type.id, name: f.crew_type.name })
    })

    return {
        years:      [...years].sort((a, b) => b - a),
        airlines:   [...airlines.values()].sort((a, b) => a.name.localeCompare(b.name)),
        countries:  [...countries.values()].sort((a, b) => a.name.localeCompare(b.name)),
        continents: [...continents.values()].sort((a, b) => a.name.localeCompare(b.name)),
        classes:    [...classes.values()].sort((a, b) => a.name.localeCompare(b.name)),
        crewTypes:  [...crewTypes.values()].sort((a, b) => a.name.localeCompare(b.name)),
    }
}

const availableOptions = buildOptions(props.flights)

// ── Filter state ──────────────────────────────────────────────────────────────
const selectedYears         = ref<number[]>([])
const selectedAirlines      = ref<number[]>([])
const selectedCountries     = ref<string[]>([])
const selectedContinents    = ref<string[]>([])
const selectedFlightClasses = ref<number[]>([])
const selectedCrewTypes     = ref<number[]>([])

function emitFilters() {
    emit('change', {
        years:         selectedYears.value,
        airlines:      selectedAirlines.value,
        countries:     selectedCountries.value,
        continents:    selectedContinents.value,
        flightClasses: selectedFlightClasses.value,
        crewTypes:     selectedCrewTypes.value,
    })
}

// ── Helpers ───────────────────────────────────────────────────────────────────
const page = usePage()
const airlineLogoUrl = (id: number) =>
    `${page.props.logo_api_url}/airlines/logos/tail/id/${id}`

const countryFlagClass = (code: string) =>
    `fi fi-${code.toLowerCase()}`
</script>

<template>
    <div class="flight-filters">
        <v-select
            v-model="selectedYears"
            :items="availableOptions.years"
            label="Year"
            multiple clearable hide-details
            density="compact" variant="outlined"
            @update:model-value="emitFilters"
        >
            <template #selection="{ item, index }">
                <span v-if="index < 2" class="v-select__selection-text">
                    {{ item }}<span v-if="index < Math.min(selectedYears.length, 2) - 1">,&nbsp;</span>
                </span>
                <span v-if="index === 2" class="text-caption text-medium-emphasis">+{{ selectedYears.length - 2 }}</span>
            </template>
        </v-select>

        <v-select
            v-model="selectedAirlines"
            :items="availableOptions.airlines"
            item-title="name" item-value="id"
            label="Airline"
            multiple clearable hide-details
            density="compact" variant="outlined"
            @update:model-value="emitFilters"
        >
            <template #item="{ item, props: itemProps }">
                <v-list-item v-bind="itemProps">
                    <template #prepend="{ isSelected }">
                        <v-checkbox-btn :model-value="isSelected" tabindex="-1" />
                    </template>
                    <template #title>
                        <img
                            :src="airlineLogoUrl((item as any).id)"
                            width="32" height="32"
                            style="object-fit: contain; margin-right: 8px; vertical-align: middle;"
                            alt=""
                        />
                        {{ (item as any).name }}
                    </template>
                </v-list-item>
            </template>
            <template #selection="{ item, index }">
                <span v-if="index < 2" class="v-select__selection-text">
                    {{ (item as any).name }}<span v-if="index < Math.min(selectedAirlines.length, 2) - 1">,&nbsp;</span>
                </span>
                <span v-if="index === 2" class="text-caption text-medium-emphasis">+{{ selectedAirlines.length - 2 }}</span>
            </template>
        </v-select>

        <v-select
            v-model="selectedCountries"
            :items="availableOptions.countries"
            item-title="name" item-value="code"
            label="Country"
            multiple clearable hide-details
            density="compact" variant="outlined"
            @update:model-value="emitFilters"
        >
            <template #item="{ item, props: itemProps }">
                <v-list-item v-bind="itemProps">
                    <template #prepend="{ isSelected }">
                        <v-checkbox-btn :model-value="isSelected" tabindex="-1" />
                    </template>
                    <template #title>
                        <span :class="countryFlagClass((item as any).code)" style="margin-right: 8px; font-size: 1.1em;" />
                        {{ (item as any).name }}
                    </template>
                </v-list-item>
            </template>
            <template #selection="{ item, index }">
                <span v-if="index < 2" class="v-select__selection-text">
                    <span :class="countryFlagClass((item as any).code)" style="margin-right: 4px;" />
                    {{ (item as any).name }}<span v-if="index < Math.min(selectedCountries.length, 2) - 1">,&nbsp;</span>
                </span>
                <span v-if="index === 2" class="text-caption text-medium-emphasis">+{{ selectedCountries.length - 2 }}</span>
            </template>
        </v-select>

        <v-select
            v-model="selectedContinents"
            :items="availableOptions.continents"
            item-title="name" item-value="code"
            label="Continent"
            multiple clearable hide-details
            density="compact" variant="outlined"
            @update:model-value="emitFilters"
        >
            <template #selection="{ item, index }">
                <span v-if="index < 2" class="v-select__selection-text">
                    {{ (item as any).name }}<span v-if="index < Math.min(selectedContinents.length, 2) - 1">,&nbsp;</span>
                </span>
                <span v-if="index === 2" class="text-caption text-medium-emphasis">+{{ selectedContinents.length - 2 }}</span>
            </template>
        </v-select>

        <v-select
            v-model="selectedFlightClasses"
            :items="availableOptions.classes"
            item-title="name" item-value="id"
            label="Flight class"
            multiple clearable hide-details
            density="compact" variant="outlined"
            @update:model-value="emitFilters"
        >
            <template #selection="{ item, index }">
                <span v-if="index < 2" class="v-select__selection-text">
                    {{ (item as any).name }}<span v-if="index < Math.min(selectedFlightClasses.length, 2) - 1">,&nbsp;</span>
                </span>
                <span v-if="index === 2" class="text-caption text-medium-emphasis">+{{ selectedFlightClasses.length - 2 }}</span>
            </template>
        </v-select>

        <v-select
            v-if="availableOptions.crewTypes.length > 0"
            v-model="selectedCrewTypes"
            :items="availableOptions.crewTypes"
            item-title="name" item-value="id"
            label="Crew Type"
            multiple clearable hide-details
            density="compact" variant="outlined"
            @update:model-value="emitFilters"
        >
            <template #selection="{ item, index }">
                <span v-if="index < 2" class="v-select__selection-text">
                    {{ (item as any).name }}<span v-if="index < Math.min(selectedCrewTypes.length, 2) - 1">,&nbsp;</span>
                </span>
                <span v-if="index === 2" class="text-caption text-medium-emphasis">+{{ selectedCrewTypes.length - 2 }}</span>
            </template>
        </v-select>
    </div>
</template>

<style scoped>
.flight-filters {
    display: flex;
    flex-wrap: wrap;
    gap: 12px;
    margin-top: 12px;
}

.flight-filters .v-select {
    flex: 1 1 160px;
}
</style>
