<script setup lang="ts">
import {Flight, User} from "@/Types/types";
import { computed, ref, watch, nextTick } from "vue";
import type { DataTableSortItem } from 'vuetify';
import {FlightStats} from "@/Composables/useFlightStats";
import DepartureBoardTableRow from "@/Components/FlightsGoneBy/DepartureBoardTableRow.vue";

const props = defineProps<{
    flightStats: FlightStats
    user: User
    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: 'REG', key: 'aircraft_registration', 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),
    departure_airport: (a: Flight['departure_airport'], b: Flight['departure_airport']) => {
        return (a?.display_code ?? '').localeCompare(b?.display_code ?? '')
    },
    arrival_airport: (a: Flight['arrival_airport'], b: Flight['arrival_airport']) => {
        return (a?.display_code ?? '').localeCompare(b?.display_code ?? '')
    },
}

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

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

const upcomingFlights = computed(() =>
    [...props.flightStats.upcomingFlights.value]
        .sort((a, b) => new Date(a.departure_date).getTime() - new Date(b.departure_date).getTime())
)

const departedFlights = computed(() =>
    [...props.flightStats.pastFlights.value]
        .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

        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">
                <DepartureBoardTableRow
                    :flight="(item as Flight)"
                    :user="user"
                    :can-edit="canEdit"
                    :highlighted="(item as any).id === flightId"
                    :group="(item as any)._group"
                    :is-sorting="isSorting"
                />
            </template>
        </template>

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

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

@media (max-width: 1200px) {
    :deep(.v-data-table__th) {
        padding: 0.75rem 4px !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;
}

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

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