<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, watch, nextTick } 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";
import {FlightStats} from "@/Composables/useFlightStats";
import GlassTooltip from "@/Components/FlightsGoneBy/GlassTooltip.vue";
import CrewTooltip from "@/Components/FlightsGoneBy/CrewTooltip.vue";

const props = defineProps<{
    flightStats: FlightStats
    canEdit: boolean
    flightId?: number | null
}>()

const ITEMS_PER_PAGE = 25

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 },
    { title: '', key: 'actions', sortable: false },
]

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),
}

const sortBy = ref<DataTableSortItem[]>([])
const currentPage = ref(1)

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

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

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

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

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

const allFlights = computed(() => [
    ...props.flightStats.upcomingFlights.value,
    ...props.flightStats.pastFlights.value,
])

const tableItems = computed(() =>
    isSorting.value ? allFlights.value : groupedItems.value
)

watch(
    [() => props.flightId, tableItems],
    async ([id]) => {
        if (!id) return

        // Count the flight's position among data rows (skipping group headers)
        const items = tableItems.value
        let dataIndex = 0
        let found = false

        for (const item of items) {
            if ((item as any)._groupHeader) continue
            if ((item as any).id === id) { found = true; break }
            dataIndex++
        }

        if (!found) return

        currentPage.value = Math.floor(dataIndex / ITEMS_PER_PAGE) + 1

        await nextTick()

        const row = document.querySelector<HTMLElement>(`tr[data-flight-id="${id}"]`)
        row?.scrollIntoView({ behavior: 'smooth', block: 'center' })
    },
    { immediate: true }
)
</script>

<template>
    <v-data-table
        :headers="headers"
        :custom-key-sort="customKeySort"
        :items="tableItems"
        :items-per-page="ITEMS_PER_PAGE"
        v-model:sort-by="sortBy"
        v-model:page="currentPage"
        class="departures-table"
        hover
    >
        <template #item="{ item, columns }">
            <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>

            <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}` : '',
                        (item as any).id === flightId ? 'flight-row--highlighted' : '',
                    ]"
                    :data-flight-id="(item as any).id"
                >
                    <td class="v-data-table__td airline-logo-cell">
                        <AirlineLogo size="32" :airline="(item as any).airline" class="airline-logo-img" />
                    </td>

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

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

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

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

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

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

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

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

                    <td class="v-data-table__td ">
                        <span class="class-cell">
                            <CrewTooltip v-if="(item as Flight).flight_reason?.name == 'Crew'" :crew-type="(item as Flight).crew_type!">
                                 <FlightClassBadge :flight="(item as Flight)" />
                            </CrewTooltip>
                            <FlightClassBadge v-else :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 !== 'Unassigned'" variant="economy">{{(item as Flight).seat_type?.name}}</InlineBadge>
                        </span>
                    </td>

                    <td class="v-data-table__td actions-cell">
                        <template v-if="canEdit">
                            <v-menu>
                                <template #activator="{ props: menuProps }">
                                    <v-btn
                                        v-bind="menuProps"
                                        icon="mdi-dots-horizontal"
                                        variant="text"
                                        size="small"
                                        density="compact"
                                    />
                                </template>
                                <v-list density="compact" bg-color="#1a1e2e">
                                    <v-list-item
                                        prepend-icon="mdi-pencil-outline"
                                        title="Edit"
                                        :href="route('flights.edit', { flight: (item as Flight).id })"
                                    />
                                </v-list>
                            </v-menu>
                        </template>
                    </td>

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

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

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

: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;
}

: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;
}

: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;
}

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

.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;
}

.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);
}

.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;
}

: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;
}

.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;
}

.no-data {
    padding: 3rem;
    text-align: center;
    font-family: 'Share Tech Mono', monospace;
    font-size: 0.8rem;
    letter-spacing: 0.2em;
    color: #445;
}

.actions-cell {
    width: 40px;
    padding: 0 0.5rem !important;
    text-align: right;
}

:deep(.v-list-item-title) {
    font-family: 'Share Tech Mono', monospace !important;
    font-size: 0.8rem !important;
    letter-spacing: 0.08em !important;
    color: #c8cdd8 !important;
}

/* ── Highlighted flight row ── */
.flight-row--highlighted {
    box-shadow: inset 3px 0 0 #ffc107;

}
.flight-row--highlighted td {
    background: rgba(255, 193, 7, 0.08) !important;
    transition: background 0.3s ease;
}
</style>
