<script lang="ts">
	import { TicketType, type FlightTicket } from "../../data/entities";
	import { Badge } from "$lib/components/ui/badge/index.js";
	import TicketItinerary from "./ticket-itinerary.svelte";

	let { data }: { data: FlightTicket } = $props();

	const outboundDuration = data.flightIteneraries.outbound.reduce(
		(acc, curr) => acc + curr.durationSeconds,
		0,
	);

	const inboundDuration = data.flightIteneraries.inbound.reduce(
		(acc, curr) => acc + curr.durationSeconds,
		0,
	);

	const isReturnTicket =
		data.flightIteneraries.inbound.length > 0 &&
		data.flightType === TicketType.Return;

	function formatDateTime(dateTimeStr: string) {
		const date = new Date(dateTimeStr);
		return {
			time: date.toLocaleTimeString("en-US", {
				hour: "2-digit",
				minute: "2-digit",
				hour12: false,
			}),
			date: date.toLocaleDateString("en-US", {
				weekday: "short",
				day: "2-digit",
				month: "short",
			}),
		};
	}

	const outboundFirst = data.flightIteneraries.outbound[0];
	const outboundLast =
		data.flightIteneraries.outbound[
			data.flightIteneraries.outbound.length - 1
		];

	const inboundFirst = isReturnTicket
		? data.flightIteneraries.inbound[0]
		: null;
	const inboundLast = isReturnTicket
		? data.flightIteneraries.inbound[
				data.flightIteneraries.inbound.length - 1
			]
		: null;

	const outboundDeparture = formatDateTime(outboundFirst.departure.localTime);
	const outboundArrival = formatDateTime(outboundLast.destination.localTime);

	const inboundDeparture = inboundFirst
		? formatDateTime(inboundFirst.departure.localTime)
		: null;
	const inboundArrival = inboundLast
		? formatDateTime(inboundLast.destination.localTime)
		: null;
</script>

{#if isReturnTicket}
	<Badge variant="outline" class="w-max">
		<span>Outbound</span>
	</Badge>
{/if}
<TicketItinerary
	departure={data.departure}
	destination={data.arrival}
	durationSeconds={outboundDuration}
	stops={data.flightIteneraries.outbound.length - 1}
	departureTime={outboundDeparture.time}
	departureDate={outboundDeparture.date}
	arrivalTime={outboundArrival.time}
	arrivalDate={outboundArrival.date}
	airlineName={outboundFirst.airline.name}
/>

{#if isReturnTicket}
	<div class="w-full border-t-2 border-dashed border-gray-400"></div>

	{#if isReturnTicket}
		<Badge variant="outline" class="w-max">
			<span>Inbound</span>
		</Badge>
	{/if}

	<TicketItinerary
		departure={data.arrival}
		destination={data.departure}
		durationSeconds={inboundDuration}
		stops={data.flightIteneraries.inbound.length - 1}
		departureTime={inboundDeparture?.time || ""}
		departureDate={inboundDeparture?.date || ""}
		arrivalTime={inboundArrival?.time || ""}
		arrivalDate={inboundArrival?.date || ""}
		airlineName={inboundFirst?.airline.name}
	/>
{:else}
	<div class="w-full border-t-2 border-dashed border-gray-400"></div>
{/if}
