<script setup lang="ts">
import MainLayout from '@/Layouts/MainLayout.vue'
import GlassBox from '@/Components/FlightsGoneBy/GlassBox.vue'
import { Head, useForm } from '@inertiajs/vue3'
import AirlineSearchBox from '@/Components/FlightsGoneBy/AirlineSearchBox.vue'
import AircraftSearchBox from '@/Components/FlightsGoneBy/AircraftSearchBox.vue'
import AirportSearchBox from '@/Components/FlightsGoneBy/AirportSearchBox.vue'
import type {SeatType, FlightReason, FlightClass, CrewType} from '@/Types/types'
import { ref, watch, computed } from 'vue'
import { VTimePicker, VDatePicker } from 'vuetify/components'

defineOptions({ layout: MainLayout })


const props = defineProps<{
    flight?: {
        id: number
        flight_number: string
        departure_date: string
        arrival_date: string
        aircraft_registration: string
        seat_number: string
        note: string
        auto_update: boolean
        seat_type: SeatType | null
        flight_class: FlightClass | null
        flight_reason: FlightReason | null
        crew_type: CrewType | null
        airline_options: { value: number; title: string; logo_url: string}[]
        from_options: { value: number; title: string; country_code: string }[]
        to_options: { value: number; title: string; country_code: string }[]
        aircraft_options: { value: number; title: string }[]
    }
    seat_types: SeatType[]
    flight_classes: FlightClass[]
    flight_reasons: FlightReason[]
    crew_types: CrewType[]
}>()

const isEdit = !!props.flight

// ── Flight number lookup ──────────────────────────────────────────────────────

const flightNumber   = ref(props.flight?.flight_number ?? '')
const lookupLoading  = ref(false)
const lookupError    = ref<string | null>(null)
const lookupComplete = ref(true)

interface LookupResult {
    airline_options:  { value: number; title: string, logo_url: string }[]
    from_options:     { value: number; title: string; country_code: string }[]
    to_options:       { value: number; title: string; country_code: string }[]
    aircraft_options: { value: number; title: string }[]
    scheduled_departure_time: string | null
    scheduled_arrival_time: string | null
}

const lookupResult = ref<LookupResult | null>(null)
const lookupKey = ref(0)

async function lookupFlight() {
    if (!flightNumber.value.trim()) return
    lookupLoading.value = true
    lookupError.value   = null
    lookupResult.value  = null

    try {
        const response = await fetch(`${route('flights.lookup')}?number=${encodeURIComponent(flightNumber.value.trim())}`, {
            headers: { Accept: 'application/json' },
        })
        const data = await response.json()
        if (!response.ok) {
            lookupError.value = data.message ?? 'Lookup failed.'
            return
        }
        lookupResult.value   = data
        lookupComplete.value = true
        if (data.airline_options?.length) {
            airlineOptionsData.value = data.airline_options
            if (!form.airline) form.airline = data.airline_options[0]
        }
        if (data.from_options?.length) {
            fromOptionsData.value = data.from_options
            if (data.from_options.length === 1 && !form.from) form.from = data.from_options[0]
        }
        if (data.to_options?.length) {
            toOptionsData.value = data.to_options
            if (data.to_options.length === 1 && !form.to) form.to = data.to_options[0]
        }
        if (data.aircraft_options?.length) {
            aircraftOptionsData.value = data.aircraft_options
            if (!form.aircraft) form.aircraft = data.aircraft_options[0]
        }

        // Populate scheduled times if the API returned them and the user
        // hasn't already entered a time themselves. Suppress the +1hr
        // auto-fill guess while doing this, since we have real data.
        suppressArrivalAutoFill = true
        const scheduledDep = normalizeTimeString(data.scheduled_departure_time)
        if (scheduledDep && !departureTimePart.value) {
            departureTimePart.value = scheduledDep
        }
        const scheduledArr = normalizeTimeString(data.scheduled_arrival_time)
        if (scheduledArr && !arrivalTimePart.value) {
            arrivalTimePart.value = scheduledArr
        }
        suppressArrivalAutoFill = false

        lookupKey.value++
    } catch (e) {
        lookupError.value = String(e)
    } finally {
        lookupLoading.value = false
    }
}

// ── Display form (drives the template) ───────────────────────────────────────

const form = useForm({
    flight_number:         props.flight?.flight_number         ?? '',
    departure_date:        props.flight?.departure_date        ?? '',
    arrival_date:          props.flight?.arrival_date          ?? '',
    from:                  props.flight?.from_options[0]       ?? null as { value: number; title: string; country_code: string } | null,
    to:                    props.flight?.to_options[0]         ?? null as { value: number; title: string; country_code: string } | null,
    airline:               props.flight?.airline_options[0]    ?? null as { value: number; title: string; logo_url: string } | null,
    aircraft:              props.flight?.aircraft_options[0]   ?? null as { value: number; title: string } | null,
    aircraft_registration: props.flight?.aircraft_registration ?? '',
    seat_number:           props.flight?.seat_number           ?? '',
    seat_type:             props.flight?.seat_type             ?? props.seat_types[0]  ?? null as SeatType | null,
    flight_class:          props.flight?.flight_class          ?? props.flight_classes[0] ?? null as FlightClass | null,
    flight_reason:         props.flight?.flight_reason         ?? props.flight_reasons[0] ?? null as FlightReason | null,
    crew_type:             props.flight?.crew_type             ?? null as CrewType | null,
    note:                  props.flight?.note                  ?? '',
    auto_update:           props.flight?.auto_update           ?? false,
})

const isCrew = computed(() => form.flight_reason?.name === 'Crew')

watch(isCrew, (val) => {
    if (!val) form.crew_type = null
})

// ── Submit form (ID-based, what actually gets sent) ───────────────────────────

const submitForm = useForm({
    flight_number:         '' as string | null,
    departure_date:        '' as string | null,
    arrival_date:          '' as string | null,
    from_id:               null as number | null,
    to_id:                 null as number | null,
    airline_id:            null as number | null,
    aircraft_id:           null as number | null,
    aircraft_registration: '' as string | null,
    seat_number:           '' as string | null,
    seat_type_id:          null as number | null,
    flight_class_id:       null as number | null,
    flight_reason_id:      null as number | null,
    crew_type_id:          null as number | null,
    note:                  '' as string | null,
    auto_update:           false,
})


const departureIsFuture = computed(() => {
    if (!form.departure_date) return false
    return new Date(form.departure_date) > new Date()
})


watch(departureIsFuture, (isFuture) => {
    form.auto_update = isFuture
}, { immediate: true })


function submit() {
    submitForm.flight_number         = flightNumber.value
    submitForm.departure_date        = form.departure_date
    submitForm.arrival_date          = form.arrival_date
    submitForm.from_id               = form.from?.value          ?? null
    submitForm.to_id                 = form.to?.value            ?? null
    submitForm.airline_id            = form.airline?.value       ?? null
    submitForm.aircraft_id           = form.aircraft?.value      ?? null
    submitForm.aircraft_registration = form.aircraft_registration
    submitForm.seat_number           = form.seat_number
    submitForm.seat_type_id          = form.seat_type?.id
    submitForm.flight_class_id       = form.flight_class?.id
    submitForm.flight_reason_id      = form.flight_reason?.id
    submitForm.crew_type_id          = form.crew_type?.id ?? null
    submitForm.note                  = form.note
    submitForm.auto_update           = form.auto_update

    if (isEdit) {
        submitForm.put(route('flights.update', { flight: props.flight!.id }))
    } else {
        submitForm.post(route('flights.store'))
    }
}

// ── Prefilled options ─────────────────────────────────────────────────────────

const airlineOptionsData  = ref<{ value: number; title: string; logo_url: string}[]>(props.flight?.airline_options ?? [])
const fromOptionsData     = ref<{ value: number; title: string; country_code: string }[]>(props.flight?.from_options ?? [])
const toOptionsData       = ref<{ value: number; title: string; country_code: string }[]>(props.flight?.to_options ?? [])
const aircraftOptionsData = ref<{ value: number; title: string }[]>(props.flight?.aircraft_options ?? [])

// ── Split date/time pickers ───────────────────────────────────────────────────
// form.departure_date / form.arrival_date stay as the single source of truth
// (YYYY-MM-DDTHH:mm strings) that the rest of the component and submit() rely
// on. These refs + watchers just give the template two separate pickers while
// keeping those combined strings in sync — no server-side changes needed.

const pad = (n: number) => String(n).padStart(2, '0')

function parseDateTime(dt: string | null | undefined) {
    if (!dt) return { date: null as Date | null, time: null as string | null }
    const d = new Date(dt)
    if (isNaN(d.getTime())) return { date: null as Date | null, time: null as string | null }
    return {
        date: new Date(d.getFullYear(), d.getMonth(), d.getDate()),
        time: `${pad(d.getHours())}:${pad(d.getMinutes())}`,
    }
}

function combineDateTime(date: Date | null, time: string | null): string {
    if (!date) return ''
    const [hh, mm] = (time ?? '00:00').split(':')
    return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${(hh ?? '00').padStart(2, '0')}:${(mm ?? '00').padStart(2, '0')}`
}

const formatDateDisplay = (d: Date | null) =>
    d ? d.toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' }) : ''

// Time is stored internally as a 24hr "HH:mm" string (VTimePicker's model
// value is always 24hr regardless of the `format` display prop). This just
// formats it for display in the read-only text fields.
function formatTimeDisplay(t: string | null): string {
    if (!t) return ''
    const [hStr, mStr] = t.split(':')
    let h = parseInt(hStr, 10)
    if (isNaN(h)) return ''
    const ampm = h >= 12 ? 'PM' : 'AM'
    h = h % 12
    if (h === 0) h = 12
    return `${h}:${mStr} ${ampm}`
}

function clearDepartureDate() { departureDatePart.value = null }
function clearDepartureTime() { departureTimePart.value = null }
function clearArrivalDate()   { arrivalDatePart.value = null }
function clearArrivalTime()   { arrivalTimePart.value = null }

// Normalizes whatever shape the API sends a scheduled time in ("14:30",
// "14:30:00", or a full datetime string) down to the internal "HH:mm" format.
function normalizeTimeString(t: string | null | undefined): string | null {
    if (!t) return null
    const match = t.match(/(\d{1,2}):(\d{2})/)
    if (match) {
        return `${match[1].padStart(2, '0')}:${match[2]}`
    }
    const d = new Date(t)
    if (!isNaN(d.getTime())) {
        return `${pad(d.getHours())}:${pad(d.getMinutes())}`
    }
    return null
}

const depInit = parseDateTime(form.departure_date)
const arrInit = parseDateTime(form.arrival_date)

const departureDatePart = ref<Date | null>(depInit.date)
const departureTimePart = ref<string | null>(depInit.time)
const arrivalDatePart   = ref<Date | null>(arrInit.date)
const arrivalTimePart   = ref<string | null>(arrInit.time)

const depDateMenu = ref(false)
const depTimeMenu = ref(false)
const arrDateMenu = ref(false)
const arrTimeMenu = ref(false)

// A short guard so programmatic updates (e.g. auto-fill of arrival) don't
// fight with the "only auto-fill once" behaviour below.
let suppressArrivalAutoFill = false

// Keep form.departure_date in sync whenever either split piece changes
watch([departureDatePart, departureTimePart], () => {
    form.departure_date = combineDateTime(departureDatePart.value, departureTimePart.value)
})

// Keep form.arrival_date in sync whenever either split piece changes
watch([arrivalDatePart, arrivalTimePart], () => {
    if (suppressArrivalAutoFill) return
    form.arrival_date = combineDateTime(arrivalDatePart.value, arrivalTimePart.value)
})

// Auto-fill arrival (+1hr) the first time a departure TIME is chosen (and a
// departure date is already set) and arrival is still empty. Picking the
// departure date alone no longer triggers this — only setting the time does.
watch(departureTimePart, (newTime) => {
    if (suppressArrivalAutoFill) return
    if (!newTime || !departureDatePart.value || arrivalDatePart.value) return

    const dep = new Date(departureDatePart.value)
    const [h, m] = newTime.split(':').map(Number)
    dep.setHours(h, m)
    const arr = new Date(dep.getTime() + 60 * 60 * 1000)

    suppressArrivalAutoFill = true
    arrivalDatePart.value = new Date(arr.getFullYear(), arr.getMonth(), arr.getDate())
    arrivalTimePart.value = `${pad(arr.getHours())}:${pad(arr.getMinutes())}`
    suppressArrivalAutoFill = false

    form.arrival_date = combineDateTime(arrivalDatePart.value, arrivalTimePart.value)
}, { flush: 'sync' })

const getArrivalBound = (form: any, offsetDays: number) => {
    if (!form.departure_date) return undefined
    const d = new Date(form.departure_date)
    d.setDate(d.getDate() + offsetDays)
    return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`
}

const arrivalMin = computed(() => getArrivalBound(form, -2))
const arrivalMax = computed(() => getArrivalBound(form, 3))

const arrivalMinDate = computed(() => arrivalMin.value ? new Date(arrivalMin.value) : undefined)
const arrivalMaxDate = computed(() => arrivalMax.value ? new Date(arrivalMax.value) : undefined)
</script>

<template>
    <Head :title="isEdit ? 'Edit Flight' : 'Add Flight'" />

    <GlassBox
        :title="isEdit ? 'Edit Flight' : 'Add Flight'"
        :blurb="isEdit
            ? 'Update the details for this flight.'
            : 'Enter a flight number then press Look Up to continue.'"
    >
        <v-form style="width: 100%">
            <v-container>

                <!-- ── Flight number + lookup ────────────────────────────── -->
                <v-row>
                    <v-col cols="12">
                        <div class="d-flex ga-3 align-start">
                            <v-text-field
                                v-model="flightNumber"
                                label="Flight Number"
                                placeholder="e.g. QF1"
                                hide-details
                                @keydown.enter="lookupFlight"
                            />
                            <v-btn
                                :loading="lookupLoading"
                                :disabled="!flightNumber.trim()"
                                size="large"
                                style="height: 56px"
                                @click="lookupFlight"
                            >
                                Look Up
                            </v-btn>
                        </div>
                        <div v-if="lookupError" class="text-error text-caption mt-1">
                            {{ lookupError }}
                        </div>
                    </v-col>
                </v-row>

                <!-- ── Departure date + time ──────────────────────────────── -->
                <v-row>
                    <v-col cols="12" sm="6">
                        <v-menu v-model="depDateMenu" :close-on-content-click="false">
                            <template #activator="{ props: menuProps }">
                                <v-text-field
                                    v-bind="menuProps"
                                    :model-value="formatDateDisplay(departureDatePart)"
                                    label="Departure Date"
                                    readonly
                                    clearable
                                    prepend-inner-icon="mdi-calendar"
                                    :disabled="!lookupComplete"
                                    :error-messages="submitForm.errors.departure_date"
                                    @click:clear="clearDepartureDate"
                                />
                            </template>
                            <v-date-picker
                                v-model="departureDatePart"
                                @update:model-value="depDateMenu = false"
                            />
                        </v-menu>
                    </v-col>
                    <v-col cols="12" sm="6">
                        <v-menu v-model="depTimeMenu" :close-on-content-click="false">
                            <template #activator="{ props: menuProps }">
                                <v-text-field
                                    v-bind="menuProps"
                                    :model-value="formatTimeDisplay(departureTimePart)"
                                    label="Departure Time"
                                    readonly
                                    clearable
                                    prepend-inner-icon="mdi-clock-outline"
                                    :disabled="!lookupComplete"
                                    @click:clear="clearDepartureTime"
                                />
                            </template>
                            <v-card>
                                <v-time-picker
                                    v-model="departureTimePart"
                                    format="ampm"
                                    scrollable
                                />
                                <v-card-actions>
                                    <v-spacer />
                                    <v-btn variant="text" @click="depTimeMenu = false">OK</v-btn>
                                </v-card-actions>
                            </v-card>
                        </v-menu>
                    </v-col>
                </v-row>

                <!-- ── Arrival date + time ─────────────────────────────────── -->
                <v-row>
                    <v-col cols="12" sm="6">
                        <v-menu v-model="arrDateMenu" :close-on-content-click="false">
                            <template #activator="{ props: menuProps }">
                                <v-text-field
                                    v-bind="menuProps"
                                    :model-value="formatDateDisplay(arrivalDatePart)"
                                    label="Arrival Date"
                                    readonly
                                    clearable
                                    prepend-inner-icon="mdi-calendar"
                                    :disabled="!lookupComplete"
                                    :error-messages="submitForm.errors.arrival_date"
                                    @click:clear="clearArrivalDate"
                                />
                            </template>
                            <v-date-picker
                                v-model="arrivalDatePart"
                                :min="arrivalMinDate"
                                :max="arrivalMaxDate"
                                @update:model-value="arrDateMenu = false"
                            />
                        </v-menu>
                    </v-col>
                    <v-col cols="12" sm="6">
                        <v-menu v-model="arrTimeMenu" :close-on-content-click="false">
                            <template #activator="{ props: menuProps }">
                                <v-text-field
                                    v-bind="menuProps"
                                    :model-value="formatTimeDisplay(arrivalTimePart)"
                                    label="Arrival Time"
                                    readonly
                                    clearable
                                    prepend-inner-icon="mdi-clock-outline"
                                    :disabled="!lookupComplete"
                                    @click:clear="clearArrivalTime"
                                />
                            </template>
                            <v-card>
                                <v-time-picker
                                    v-model="arrivalTimePart"
                                    format="ampm"
                                    scrollable
                                />
                                <v-card-actions>
                                    <v-spacer />
                                    <v-btn variant="text" @click="arrTimeMenu = false">OK</v-btn>
                                </v-card-actions>
                            </v-card>
                        </v-menu>
                    </v-col>
                </v-row>

                <!-- ── From ──────────────────────────────────────────────── -->
                <v-row>
                    <v-col cols="12">
                        <AirportSearchBox
                            v-model="form.from"
                            label="From"
                            :prefilled-options="fromOptionsData"
                            :error-messages="submitForm.errors.from_id"
                            :disabled="!lookupComplete"
                        />
                    </v-col>
                </v-row>

                <!-- ── To ────────────────────────────────────────────────── -->
                <v-row>
                    <v-col cols="12">
                        <AirportSearchBox
                            v-model="form.to"
                            label="To"
                            :prefilled-options="toOptionsData"
                            :error-messages="submitForm.errors.to_id"
                            :disabled="!lookupComplete"
                        />
                    </v-col>
                </v-row>

                <!-- ── Airline ────────────────────────────────────────────── -->
                <v-row>
                    <v-col cols="12">
                        <AirlineSearchBox
                            :key="`airline-${lookupKey}`"
                            v-model="form.airline"
                            :prefilled-options="airlineOptionsData"
                            :error-messages="submitForm.errors.airline_id"
                            :disabled="!lookupComplete"
                        />
                    </v-col>
                </v-row>

                <!-- ── Aircraft ───────────────────────────────────────────── -->
                <v-row>
                    <v-col cols="12">
                        <AircraftSearchBox
                            :key="`aircraft-${lookupKey}`"
                            v-model="form.aircraft"
                            :prefilled-options="aircraftOptionsData"
                            :error-messages="submitForm.errors.aircraft_id"
                            :disabled="!lookupComplete"
                        />
                    </v-col>
                </v-row>

                <!-- ── Registration + Flight class ────────────────────────── -->
                <v-row>
                    <v-col cols="12" md="6">
                        <v-text-field
                            v-model="form.aircraft_registration"
                            label="Aircraft Registration"
                            placeholder="e.g. VH-OQA"
                            :disabled="!lookupComplete"
                            :error-messages="submitForm.errors.aircraft_registration"
                        />
                    </v-col>
                    <v-col cols="12" md="6">
                        <v-select
                            v-model="form.flight_class"
                            label="Flight Class"
                            :items="flight_classes"
                            item-title="name"
                            item-value="id"
                            :return-object="true"
                            :disabled="!lookupComplete"
                            :error-messages="submitForm.errors.flight_class_id"
                        />
                    </v-col>
                </v-row>

                <!-- ── Seat number + Seat type ────────────────────────────── -->
                <v-row>
                    <v-col cols="12" md="6">
                        <v-text-field
                            v-model="form.seat_number"
                            label="Seat Number"
                            placeholder="e.g. 12A"
                            :disabled="!lookupComplete"
                            :error-messages="submitForm.errors.seat_number"
                        />
                    </v-col>
                    <v-col cols="12" md="6">
                        <v-select
                            v-model="form.seat_type"
                            label="Seat Type"
                            :items="seat_types"
                            item-title="name"
                            item-value="id"
                            :return-object="true"
                            :disabled="!lookupComplete"
                            :error-messages="submitForm.errors.seat_type_id"
                        />
                    </v-col>
                </v-row>

                <!-- ── Flight reason + Crew type ──────────────────────────── -->
                <v-row>
                    <v-col cols="12" md="6">
                        <v-select
                            v-model="form.flight_reason"
                            label="Flight Reason"
                            :items="flight_reasons"
                            item-title="name"
                            item-value="id"
                            :return-object="true"
                            :disabled="!lookupComplete"
                            :error-messages="submitForm.errors.flight_reason_id"
                        />
                    </v-col>
                    <v-col v-if="isCrew" cols="12" md="6">
                        <v-select
                            v-model="form.crew_type"
                            label="Crew Type"
                            :items="crew_types"
                            item-title="name"
                            item-value="id"
                            :return-object="true"
                            :disabled="!lookupComplete"
                            :error-messages="submitForm.errors.crew_type_id"
                        />
                    </v-col>
                </v-row>

                <!-- ── Note ──────────────────────────────────────────────── -->
                <v-row>
                    <v-col cols="12">
                        <v-textarea
                            v-model="form.note"
                            label="Note"
                            placeholder="Any additional notes…"
                            :disabled="!lookupComplete"
                            :error-messages="submitForm.errors.note"
                            rows="3"
                            auto-grow
                        />
                    </v-col>
                </v-row>

                <!-- ── Auto update ────────────────────────────────────────── -->
                <v-row v-if="departureIsFuture">
                    <v-col cols="12">
                        <v-checkbox
                            v-model="form.auto_update"
                            label="Automatically update flight details within 24 hours of flight departure"
                            :disabled="!lookupComplete"
                            hide-details
                            density="compact"
                        />
                    </v-col>
                </v-row>

                <!-- ── Submit ─────────────────────────────────────────────── -->
                <v-row>
                    <v-col cols="12">
                        <v-btn
                            block
                            size="large"
                            :loading="submitForm.processing"
                            :disabled="!lookupComplete || submitForm.processing"
                            @click="submit"
                        >
                            {{ isEdit ? 'Save Changes' : 'Add Flight' }}
                        </v-btn>
                    </v-col>
                </v-row>

            </v-container>
        </v-form>
    </GlassBox>
</template>

<style scoped>
</style>
