<script setup lang="ts">

import FlightClassBadge from "@/Components/FlightsGoneBy/FlightClassBadge.vue";
import AirlineLogo from "@/Components/FlightsGoneBy/AirlineLogo.vue";
import {Flight} from "@/Types/types";
import { computed, ref } from "vue";
import type { DataTableSortItem } from 'vuetify';
import InlineBadge from "@/Components/FlightsGoneBy/InlineBadge.vue";
import AirportToolTip from "@/Components/FlightsGoneBy/AirportToolTip.vue";
import AircraftToolTip from "@/Components/FlightsGoneBy/AircraftToolTip.vue";

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

const headers = [
    { title: '', key: 'airline', sortable: true },
    { title: 'FLIGHT', key: 'flight_number', sortable: true },
    { title: 'FROM', key: 'departure_airport', sortable: true },
    { title: 'TO', key: 'arrival_airport', sortable: true },
    { title: 'DATE', key: 'departure_date', sortable: true },
    { title: 'DEPART', key: 'departure_time_display', sortable: false },
    { title: 'ARRIVE', key: 'arrival_time_display', sortable: false },
    { title: 'DURATION', key: 'duration', sortable: true },
    { title: 'DISTANCE', key: 'distance', sortable: true },
    { title: 'AIRCRAFT', key: 'aircraft.designator', sortable: true },
    { title: 'CLASS', key: 'flight_class', sortable: true },
]

const CLASS_ORDER: Record<string, number> = {
    'Unspecified': 0,
    'Economy': 1,
    'Premium Economy': 2,
    'Business': 3,
    'First': 4,
    'Private': 5
}

const customKeySort = {
    flight_class: (a: Flight['flight_class'], b: Flight['flight_class']) => {
        return (CLASS_ORDER[a?.name ?? ''] ?? -1) - (CLASS_ORDER[b?.name ?? ''] ?? -1)
    },
    airline: (a: Flight['airline'], b: Flight['airline']) => {
        return (a?.IATA_code ?? '').localeCompare(b?.IATA_code ?? '')
    },
    duration: (a: any, b: any) => (a ?? 0) - (b ?? 0),
}

// Track active sort state
const sortBy = ref<DataTableSortItem[]>([])

const today = new Date()
today.setHours(0, 0, 0, 0)

const isSorting = computed(() => sortBy.value.length > 0)

// Split flights into upcoming vs departed, sorted by date within each group
const upcomingFlights = computed(() =>
    props.flights
        .filter(f => new Date(f.departure_date) >= today)
        .sort((a, b) => new Date(a.departure_date).getTime() - new Date(b.departure_date).getTime())
)

const departedFlights = computed(() =>
    props.flights
        .filter(f => new Date(f.departure_date) < today)
        .sort((a, b) => new Date(b.departure_date).getTime() - new Date(a.departure_date).getTime())
)

// Flat ordered list with group markers injected — used only when not sorting
type GroupedFlight = Flight & { _group?: 'upcoming' | 'departed'; _groupHeader?: boolean; _groupLabel?: string }

const groupedItems = computed<GroupedFlight[]>(() => {
    const result: GroupedFlight[] = []

    if (upcomingFlights.value.length > 0) {
        result.push({ _groupHeader: true, _groupLabel: 'UPCOMING FLIGHTS', _group: 'upcoming' } as GroupedFlight)
        upcomingFlights.value.forEach(f => result.push({ ...f, _group: 'upcoming' }))
    }

    if (departedFlights.value.length > 0) {
        result.push({ _groupHeader: true, _groupLabel: 'DEPARTED FLIGHTS', _group: 'departed' } as GroupedFlight)
        departedFlights.value.forEach(f => result.push({ ...f, _group: 'departed' }))
    }

    return result
})

// When sorting, pass all flights flat; when not sorting, pass grouped (headers will be rendered via #item slot trick)
const tableItems = computed(() =>
    isSorting.value ? props.flights : groupedItems.value
)
</script>

<template>
    <v-data-table
        :headers="headers"
        :custom-key-sort="customKeySort"
        :items="tableItems"
        :items-per-page="25"
        v-model:sort-by="sortBy"
        class="departures-table"
        hover
    >
        <!-- ── GROUP HEADER ROW (injected as a fake item) ── -->
        <template #item="{ item, columns }">
            <!-- Section divider row -->
            <template v-if="(item as any)._groupHeader && !isSorting">
                <tr class="section-header-row">
                    <td :colspan="columns.length" class="section-header-cell">
                        <div class="section-header-inner" :class="(item as any)._group">
                            <span class="section-header-icon">
                                {{ (item as any)._group === 'upcoming' ? '◈' : '◉' }}
                            </span>
                            <span class="section-header-label">{{ (item as any)._groupLabel }}</span>
                            <span class="section-header-count">
                                {{
                                    (item as any)._group === 'upcoming'
                                        ? upcomingFlights.length
                                        : departedFlights.length
                                }} {{ (item as any)._group === 'upcoming' ? 'scheduled' : 'logged' }}
                            </span>
                            <div class="section-header-line" />
                        </div>
                    </td>
                </tr>
            </template>

            <!-- Normal data row -->
            <template v-else-if="!(item as any)._groupHeader">
                <tr
                    class="v-data-table__tr"
                    :class="(item as any)._group && !isSorting ? `group-row--${(item as any)._group}` : ''"
                >
                    <!-- Airline logo -->
                    <td class="v-data-table__td airline-logo-cell">
                        <AirlineLogo size="32" :airline="(item as any).airline" class="airline-logo-img" />
                    </td>

                    <!-- Flight number -->
                    <td class="v-data-table__td flight-number-cell">
                        <div class="flight-cell">
                            <span class="flight-number">{{ (item as any).flight_number }}</span>
                        </div>
                    </td>

                    <!-- Departure airport -->
                    <td class="v-data-table__td">
                        <AirportToolTip :airport="(item as Flight).departure_airport">
                                <span class="iata">{{ (item as Flight).departure_airport.iata_code }}</span><br/>
                        </AirportToolTip>
                            <span class="city-name">{{ (item as Flight).departure_airport.municipality }}</span>

                    </td>

                    <!-- Arrival airport -->
                    <td class="v-data-table__td">
                        <AirportToolTip :airport="(item as Flight).arrival_airport">
                            <span class="iata">{{ (item as Flight).arrival_airport.iata_code }}</span><br/>
                        </AirportToolTip>
                        <span class="city-name">{{ (item as Flight).arrival_airport.municipality }}</span>
                    </td>

                    <!-- Departure date -->
                    <td class="v-data-table__td">
                        <span class="date-cell">{{ (item as Flight).departure_date_display }}</span>
                    </td>

                    <!-- Departure time -->
                    <td class="v-data-table__td">
                        <span class="time-cell">{{ (item as Flight).departure_time_display }}</span>
                    </td>

                    <!-- Arrival time -->
                    <td class="v-data-table__td">
                        <span class="time-cell">{{ (item as Flight).arrival_time_display }}</span>
                        <sup v-if="(item as Flight).arrival_day_difference" class="day-diff">
                            +{{ (item as Flight).arrival_day_difference }}
                        </sup>
                    </td>

                    <td class="v-data-table__td">
                        <span class="mono-tag">{{ (item as Flight).duration_display ?? '—' }}</span>
                    </td>

                    <!-- Distance -->
                    <td class="v-data-table__td">
                    <span class="mono-tag distance-cell">
                        {{ (item as Flight).distance ? Math.round((item as Flight).distance).toLocaleString() + ' km' : '' }}
                    </span>
                    </td>

                    <!-- Aircraft -->
                    <td class="v-data-table__td">
                        <AircraftToolTip v-if="(item as any).aircraft" :aircraft="(item as any).aircraft">
                            <span class="mono-tag">{{ (item as any).aircraft?.designator }}</span>
                        </AircraftToolTip>
                    </td>

                    <!-- Class -->
                    <td class="v-data-table__td ">
                        <span class="class-cell">
                        <FlightClassBadge :flight="(item as Flight)" />
                        <InlineBadge v-if="(item as Flight).seat_number" variant="economy">{{(item as Flight).seat_number}}</InlineBadge>
                        <InlineBadge v-if="(item as Flight).seat_type?.name && (item as Flight).seat_type?.name !== 'Unspecified'" variant="economy">{{(item as Flight).seat_type?.name}}</InlineBadge>
                        </span>
                    </td>

                </tr>
            </template>
        </template>

        <!-- Empty state -->
        <template #no-data>
            <div class="no-data">
                <span>NO FLIGHTS ON RECORD</span>
            </div>
        </template>
    </v-data-table>
</template>

<style scoped>
/* ── Vuetify table overrides ── */
.departures-table {
    background: transparent !important;
    color: #c8cdd8 !important;
    font-family: 'Barlow', sans-serif !important;
}

/* Header row */
:deep(.v-data-table-header__content) {
    font-family: 'Share Tech Mono', monospace !important;
    font-size: 0.68rem !important;
    letter-spacing: 0.14em !important;
    color: #ffc107 !important;
    font-weight: 400 !important;
}

:deep(.v-data-table__th) {
    background: transparent !important;
    border-bottom: 1px solid rgba(255,193,7,0.15) !important;
    padding: 0.75rem 1rem !important;
}

/* Body rows — alternating, no borders */
:deep(.v-data-table__tr:nth-child(odd)) {
    background: rgba(255,255,255,0.025) !important;
}

:deep(.v-data-table__tr:nth-child(even)) {
    background: transparent !important;
}

:deep(.v-data-table__tr:hover td) {
    background: rgba(255,193,7,0.05) !important;
}

:deep(.v-data-table__td) {
    border: none !important;
    padding: 0.7rem 1rem !important;
    font-size: 0.88rem !important;
    color: #c8cdd8 !important;
}

/* Footer / pagination */
:deep(.v-data-table-footer) {
    background: transparent !important;
    border-top: 1px solid rgba(255,255,255,0.06) !important;
    color: #556 !important;
    font-family: 'Share Tech Mono', monospace !important;
    font-size: 0.75rem !important;
}

:deep(.v-data-table-footer .v-btn) {
    color: #778 !important;
}

:deep(.v-data-table-footer .v-btn--active) {
    color: #ffc107 !important;
}

/* Sort icon colour */
:deep(.v-data-table-header__sort-icon) {
    color: #ffc107 !important;
    opacity: 0.5;
}

/* ── Section header rows ── */
.section-header-row {
    background: transparent !important;
}

.section-header-cell {
    padding: 0 !important;
    border: none !important;
}

.section-header-inner {
    display: flex;
    align-items: center;
    gap: 0.75rem;
    padding: 1.5rem 1rem 0.6rem;
    position: relative;
}

/* Upcoming = amber accent */
.section-header-inner.upcoming .section-header-icon,
.section-header-inner.upcoming .section-header-label {
    color: #ffc107;
}

.section-header-inner.upcoming .section-header-line {
    background: linear-gradient(to right, rgba(255,193,7,0.4), transparent);
}

/* Departed = muted slate */
.section-header-inner.departed .section-header-icon,
.section-header-inner.departed .section-header-label {
    color: #778899;
}

.section-header-inner.departed .section-header-line {
    background: linear-gradient(to right, rgba(119,136,153,0.35), transparent);
}

.section-header-icon {
    font-size: 0.7rem;
    flex-shrink: 0;
}

.section-header-label {
    font-family: 'Share Tech Mono', monospace;
    font-size: 0.72rem;
    letter-spacing: 0.22em;
    font-weight: 400;
    flex-shrink: 0;
    text-transform: uppercase;
}

.section-header-count {
    font-family: 'Share Tech Mono', monospace;
    font-size: 0.65rem;
    letter-spacing: 0.1em;
    color: #445566;
    flex-shrink: 0;
    text-transform: uppercase;
}

.section-header-line {
    flex: 1;
    height: 1px;
    min-width: 2rem;
}

/* ── Airline + flight number fused cells ── */
:deep(.v-data-table__th:nth-child(1)) {
    width: 50px !important;
    min-width: 50px !important;
    max-width: 50px !important;
    padding-right: 0 !important;
}

:deep(.v-data-table__th:nth-child(2)) {
    padding-left: 0.5rem !important;
}

.airline-logo-cell {
    width: 50px !important;
    min-width: 50px !important;
    max-width: 50px !important;
    padding-right: 0 !important;
}

.flight-number-cell {
    padding-left: 0.5rem !important;
}

/* ── Cell styles ── */
.flight-cell {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    cursor: pointer;
}

.airline-logo-img {
    opacity: 0.85;
    flex-shrink: 0;
}

.flight-number {
    font-family: 'Share Tech Mono', monospace;
    font-size: 0.9rem;
    color: #e8eaf0;
    letter-spacing: 0.06em;
}

.iata {
    display: inline-block;
    font-family: 'Share Tech Mono', monospace;
    font-size: 1rem;
    font-weight: 600;
    color: #e8eaf0;
    letter-spacing: 0.08em;
    margin-right: 0.35rem;
}

.city-name {
    font-size: 0.75rem;
    color: #556;
    text-transform: uppercase;
    letter-spacing: 0.05em;
}

.date-cell {
    font-family: 'Share Tech Mono', monospace;
    font-size: 0.82rem;
    color: #9aa;
    letter-spacing: 0.04em;
}

.time-cell {
    font-family: 'Share Tech Mono', monospace;
    font-size: 0.82rem;
    color: #c8cdd8;
    letter-spacing: 0.04em;
}

.day-diff {
    font-family: 'Share Tech Mono', monospace;
    font-size: 0.65rem;
    color: #ffc107;
    letter-spacing: 0.04em;
    margin-left: 0.15rem;
}

.mono-tag {
    font-family: 'Share Tech Mono', monospace;
    font-size: 0.8rem;
    color: #778899;
    letter-spacing: 0.06em;
}

.seat-cell {
    font-family: 'Share Tech Mono', monospace;
    font-size: 0.85rem;
    color: #c8cdd8;
}

.class-cell {
    display: flex;
    align-items: center;
    gap: 0.5rem;
}

/* ── Empty state ── */
.no-data {
    padding: 3rem;
    text-align: center;
    font-family: 'Share Tech Mono', monospace;
    font-size: 0.8rem;
    letter-spacing: 0.2em;
    color: #445;
}
</style>
