<script setup lang="ts">
import type { Trip } from '~/server/utils/flightics'

const props = defineProps<{
  from: string
  to: string
}>()

const { trips, loading, fetchRouteFlights } = useRouteFlights()

onMounted(() => {
  if (props.from && props.to) {
    fetchRouteFlights(props.from, props.to)
  }
})

function formatTime(d: string) {
  return new Date(d).toLocaleTimeString('es-ES', { hour: '2-digit', minute: '2-digit' })
}

function formatDate(d: string) {
  return new Date(d).toLocaleDateString('es-ES', { day: 'numeric', month: 'short' })
}
</script>

<template>
  <div v-if="loading || trips.length > 0">
    <h3 class="font-semibold mb-3">Otros vuelos {{ from }} → {{ to }}</h3>
    <div v-if="loading" class="space-y-2">
      <USkeleton v-for="i in 3" :key="i" class="h-12" />
    </div>
    <div v-else class="space-y-2">
      <div
        v-for="(trip, i) in trips.slice(0, 5)"
        :key="i"
        class="flex items-center justify-between px-3 py-2 rounded-lg border border-neutral-200 dark:border-neutral-700 text-sm"
      >
        <div class="flex items-center gap-4">
          <span class="font-medium">
            {{ formatTime(trip.legs[0]?.segments[0]?.departureDate) }}
            →
            {{ formatTime(trip.legs[0]?.segments.at(-1)?.arrivalDate || '') }}
          </span>
          <span class="text-muted">
            {{ formatDate(trip.legs[0]?.segments[0]?.departureDate) }}
          </span>
          <span class="text-xs text-muted">
            {{ trip.legs[0]?.segments[0]?.company?.code }}{{ trip.legs[0]?.segments[0]?.number }}
          </span>
        </div>
        <span class="font-bold text-primary-600 dark:text-primary-400">
          {{ trip.totalCost.toFixed(0) }}&euro;
        </span>
      </div>
    </div>
  </div>
</template>
