<script setup lang="ts">
import {Flight, SharedProps, 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";
import {usePage} from "@inertiajs/vue3";

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


const page = usePage<SharedProps>().props
const ITEMS_PER_PAGE = 25

const defaultColumns = ['airline', 'flight_number', 'departure_airport', 'arrival_airport', 'departure_date', 'departure_time', 'arrival_time', 'duration', 'distance', 'aircraft', 'registration', 'class_seat_combined']
const columnsToShow = computed(() => page.auth.user?.resolved_settings?.departure_board_columns ?? defaultColumns)
const showColumn = (column: string) => columnsToShow.value.includes(column)

const allHeaders = [
    { title: '', key: 'airline', sortable: true, resizable: false},
    { title: 'FLIGHT', key: 'flight_number', sortable: true },
    { title: 'AIRLINE', key: 'airline.name', sortable: true},
    { title: 'IATA', key: 'airline.iata_code', sortable: true},
    { title: 'ICAO', key: 'airline.icao_code', 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', sortable: false },
    { title: 'ARRIVE', key: 'arrival_time', sortable: false },
    { title: 'DURATION', key: 'duration', sortable: true },
    { title: 'DISTANCE', key: 'distance', sortable: true },
    { title: 'MANUFACTURER', key: 'aircraft.manufacturer_code', sortable: true },
    { title: 'MODEL', key: 'aircraft.model_full_name', sortable: true },
    { title: 'AIRCRAFT', key: 'aircraft.display_name_short', sortable: true },
    { title: 'AIRCRAFT', key: 'aircraft', sortable: true },
    { title: 'REG', key: 'registration', sortable: true },
    { title: 'CLASS', key: 'flight_class', sortable: true },
    { title: 'CLASS', key: 'class_seat_combined', sortable: true },
    { title: 'SEAT TYPE', key: 'seat_type_id', sortable: true },
    { title: 'SEAT NO.', key: 'seat_number', sortable: true },
    { title: 'REASON', key: 'flight_reason_id', sortable: true },
    { title: '', key: 'actions', sortable: false },
]

const headers = computed(() =>
    allHeaders.filter(h => h.key === 'actions' || showColumn(h.key))
)

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

const customKeySort = {
    flight_class: (a: Flight['flight_class'], b: Flight['flight_class']) => (CLASS_ORDER[a?.name ?? ''] ?? -1) - (CLASS_ORDER[b?.name ?? ''] ?? -1),
    class_seat_combined: (a: Flight['class_seat_combined'], b: Flight['class_seat_combined']) => (CLASS_ORDER[a] ?? -1) - (CLASS_ORDER[b] ?? -1),
    airline: (a: Flight['airline'], b: Flight['airline']) => (a?.iata_code ?? '').localeCompare(b?.iata_code ?? ''),
    aircraft: (a: Flight['aircraft'], b: Flight['aircraft']) => (a?.designator ?? '').localeCompare(b?.designator ?? ''),
    duration: (a: any, b: any) => (a ?? 0) - (b ?? 0),
    departure_airport: (a: Flight['departure_airport'], b: Flight['departure_airport']) => (a?.display_code ?? '').localeCompare(b?.display_code ?? ''),
    arrival_airport: (a: Flight['arrival_airport'], b: Flight['arrival_airport']) => (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
                    :columnsToShow="columnsToShow"
                    :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>
