<script setup lang="ts">
import MainLayout from "@/Layouts/MainLayout.vue";
import { Head } from '@inertiajs/vue3'
import { ref, computed, defineAsyncComponent } from 'vue'
import { Flight, ProfileView, User } from "@/Types/types"
import { router } from '@inertiajs/vue3'
import { useFlightStats, FlightStats } from "@/Composables/useFlightStats"
import ProfileViewSwitcher from "@/Components/FlightsGoneBy/ProfileViewSwitcher.vue"
import ProfileLayout from "@/Components/FlightsGoneBy/ProfileLayout.vue"
import DepartureBoard from "@/Components/FlightsGoneBy/DepartureBoard.vue"
import BoardingPasses from "@/Components/FlightsGoneBy/BoardingPasses.vue";
import FlightMapAndCharts from "@/Components/FlightsGoneBy/FlightMapAndCharts.vue";

defineOptions({ layout: MainLayout })

const props = defineProps<{
    user: User
    flights: Flight[]
    canEdit: boolean
    initialView?: ProfileView
}>()

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

function onFiltersChange(filters: {
    years: number[]
    airlines: number[]
    countries: string[]
    continents: string[]
    flightClasses: number[]
}) {
    selectedYears.value         = filters.years
    selectedAirlines.value      = filters.airlines
    selectedCountries.value     = filters.countries
    selectedContinents.value    = filters.continents
    selectedFlightClasses.value = filters.flightClasses
}

function matchesFilters(f: Flight): boolean {
    const date = new Date(f.departure_date)
    if (selectedYears.value.length && !selectedYears.value.includes(date.getFullYear())) return false
    if (selectedAirlines.value.length && !selectedAirlines.value.includes(f.airline?.id ?? -1)) return false
    if (selectedCountries.value.length) {
        const depCode = f.departure_airport.region?.country?.code
        const arrCode = f.arrival_airport.region?.country?.code
        if (!selectedCountries.value.includes(depCode ?? '') && !selectedCountries.value.includes(arrCode ?? '')) return false
    }
    if (selectedContinents.value.length) {
        const depCode = f.departure_airport.region?.continent?.code
        const arrCode = f.arrival_airport.region?.continent?.code
        if (!selectedContinents.value.includes(depCode ?? '') && !selectedContinents.value.includes(arrCode ?? '')) return false
    }
    if (selectedFlightClasses.value.length && !selectedFlightClasses.value.includes(f.flight_class?.id ?? -1)) return false
    return true
}

const filteredFlights = computed(() => props.flights.filter(matchesFilters))

const stats = useFlightStats(filteredFlights)

// ── View switching ────────────────────────────────────────────────────────────
const activeView = ref<ProfileView>(props.initialView ?? 'board')

const routeNames = {
    map:    'profile.map',
    board:  'profile.departure-board',
    passes: 'profile.boarding-passes',
} as const

function switchView(view: ProfileView) {
    activeView.value = view
    window.history.replaceState(
        window.history.state,
        '',
        route(routeNames[view], { username: props.user.name })
    )
}
</script>

<template>
    <Head :title="`${user.name}'s Flights`" />
    <ProfileLayout :flights="flights" :user="user">
        <ProfileViewSwitcher :active-view="activeView" @update:active-view="switchView" />
        <DepartureBoard v-if="activeView === 'board'" :flight-stats="stats" :canEdit="canEdit" />
        <BoardingPasses v-else-if="activeView === 'passes'" :flight-stats="stats" :canEdit="canEdit" />
        <FlightMapAndCharts
            v-else-if="activeView === 'map'"
            :stats="stats"
            :canEdit="canEdit"
            @filters-change="onFiltersChange"
        />
    </ProfileLayout>
</template>
