<script lang="ts">
	import { post } from '$lib/api/client';
	import type { Transportation } from '$lib/api/types';
	import PlacesAutocomplete from './PlacesAutocomplete.svelte';
	import ImageUpload from './ImageUpload.svelte';

	let {
		transport = null,
		tripId,
		tripStart = '',
		tripEnd = '',
		onSave,
		onDelete,
		onClose
	}: {
		transport: Transportation | null;
		tripId: string;
		tripStart?: string;
		tripEnd?: string;
		onSave: (t: any) => void;
		onDelete: (id: string) => void;
		onClose: () => void;
	} = $props();

	let modal = $state<HTMLDialogElement | null>(null);
	let saving = $state(false);
	let deleting = $state(false);
	let confirmDelete = $state(false);
	let flightStatus = $state<any>(null);
	let checkingFlight = $state(false);

	let form = $state({
		name: '', type: 'plane', flight_number: '', from_location: '', to_location: '',
		date: '', end_date: '', timezone: '', description: '', link: '',
		cost_points: 0, cost_cash: 0, from_place_id: '', to_place_id: ''
	});

	let isEdit = $derived(!!transport?.id);
	let images = $derived((transport as any)?.images || []);

	$effect(() => {
		if (transport) {
			form = {
				name: transport.name || '', type: transport.type || 'plane',
				flight_number: transport.flight_number || '',
				from_location: transport.from_location || '', to_location: transport.to_location || '',
				date: transport.date || '', end_date: transport.end_date || '',
				timezone: transport.timezone || '', description: transport.description || '',
				link: transport.link || '', cost_points: transport.cost_points || 0,
				cost_cash: transport.cost_cash || 0,
				from_place_id: transport.from_place_id || '', to_place_id: transport.to_place_id || ''
			};
		}
		modal?.showModal();
	});

	async function save() {
		saving = true;
		try {
			const payload = { ...form, trip_id: tripId };
			if (isEdit) {
				(payload as any).id = transport!.id;
				await post('/api/transportation/update', payload);
			} else {
				await post('/api/transportation', payload);
			}
			onSave(payload);
		} catch (e) { console.error('Failed to save transport:', e); }
		finally { saving = false; }
	}

	async function doDelete() {
		if (!transport?.id) return;
		deleting = true;
		try {
			await post('/api/transportation/delete', { id: transport.id });
			onDelete(transport.id);
		} catch (e) { console.error('Failed to delete:', e); }
		finally { deleting = false; }
	}

	async function checkFlightStatus() {
		if (!form.flight_number) return;
		checkingFlight = true;
		try {
			flightStatus = await post('/api/flight-status', {
				flight_number: form.flight_number,
				date: form.date?.split('T')[0] || ''
			});
		} catch { flightStatus = { error: 'Failed to check status' }; }
		finally { checkingFlight = false; }
	}

	function close() { modal?.close(); onClose(); }
</script>

<dialog bind:this={modal} class="modal modal-bottom sm:modal-middle" onclose={onClose}>
	<div class="modal-box max-w-2xl max-h-[85vh] overflow-y-auto">
		<form method="dialog">
			<button class="btn btn-sm btn-circle btn-ghost absolute right-2 top-2">&#x2715;</button>
		</form>

		<h3 class="font-bold text-lg flex items-center gap-2 mb-4">
			<div class="p-2 rounded-xl bg-info/15">
				<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 text-info" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
					<path d="M22 16.21v-1.895L14 8.42V4a2 2 0 1 0-4 0v4.42L2 14.315v1.895l8-2.526V18l-2 1.5V21l4-1 4 1v-1.5L16 18v-4.316z"/>
				</svg>
			</div>
			{isEdit ? 'Edit Transport' : 'New Transport'}
		</h3>

		{#if isEdit}
			<div class="mb-4">
				<ImageUpload entityType="transportation" entityId={transport?.id || ''} {images} documents={(transport as any)?.documents || []} entityName={form.name || form.flight_number || ''} {tripStart} {tripEnd} onUpload={() => onSave({})} />
			</div>
		{/if}

		<form onsubmit={(e) => { e.preventDefault(); save(); }}>
			<div class="space-y-3">
				<div class="grid grid-cols-2 gap-3">
					<div class="form-control">
						<label class="label"><span class="label-text">Name</span></label>
						<input type="text" class="input input-bordered w-full" bind:value={form.name} placeholder="e.g. United Airlines" />
					</div>
					<div class="form-control">
						<label class="label"><span class="label-text">Type</span></label>
						<select class="select select-bordered w-full" bind:value={form.type}>
							<option value="plane">Flight</option>
							<option value="train">Train</option>
							<option value="car">Car</option>
							<option value="bus">Bus</option>
							<option value="ferry">Ferry</option>
						</select>
					</div>
				</div>

				<div class="form-control">
					<label class="label"><span class="label-text">Flight / Reference #</span></label>
					<div class="flex gap-2">
						<input type="text" class="input input-bordered flex-1" bind:value={form.flight_number} placeholder="e.g. UA 1234" />
						{#if form.type === 'plane' && form.flight_number}
							<button type="button" class="btn btn-outline btn-sm self-center" onclick={checkFlightStatus} disabled={checkingFlight}>
								{#if checkingFlight}<span class="loading loading-spinner loading-xs"></span>{:else}Status{/if}
							</button>
						{/if}
					</div>
				</div>

				{#if flightStatus && !flightStatus.error}
					<div class="bg-base-300/50 rounded-lg p-3 text-sm space-y-1">
						{#if flightStatus.status}<div class="font-medium text-base-content">{flightStatus.status}</div>{/if}
						{#if flightStatus.departure}<div class="text-base-content/60">Departure: {flightStatus.departure}</div>{/if}
						{#if flightStatus.arrival}<div class="text-base-content/60">Arrival: {flightStatus.arrival}</div>{/if}
						{#if flightStatus.gate}<div class="text-base-content/60">Gate: {flightStatus.gate}</div>{/if}
						{#if flightStatus.terminal}<div class="text-base-content/60">Terminal: {flightStatus.terminal}</div>{/if}
					</div>
				{:else if flightStatus?.error}
					<div class="text-xs text-error">{flightStatus.error}</div>
				{/if}

				<div class="grid grid-cols-2 gap-3">
					<div class="form-control">
						<label class="label"><span class="label-text">From</span></label>
						<PlacesAutocomplete
							bind:value={form.from_location}
							placeholder="e.g. DFW"
							onSelect={(details) => { form.from_place_id = details.place_id || ''; }}
						/>
					</div>
					<div class="form-control">
						<label class="label"><span class="label-text">To</span></label>
						<PlacesAutocomplete
							bind:value={form.to_location}
							placeholder="e.g. LAX"
							onSelect={(details) => { form.to_place_id = details.place_id || ''; }}
						/>
					</div>
				</div>

				<div class="grid grid-cols-2 gap-3">
					<div class="form-control">
						<label class="label"><span class="label-text">Departure</span></label>
						<input type="datetime-local" class="input input-bordered w-full" bind:value={form.date} />
					</div>
					<div class="form-control">
						<label class="label"><span class="label-text">Arrival</span></label>
						<input type="datetime-local" class="input input-bordered w-full" bind:value={form.end_date} />
					</div>
				</div>

				<div class="form-control">
					<label class="label"><span class="label-text">Description</span></label>
					<textarea class="textarea textarea-bordered w-full" rows="2" bind:value={form.description}></textarea>
				</div>

				<div class="form-control">
					<label class="label"><span class="label-text">Link</span></label>
					<input type="url" class="input input-bordered w-full" bind:value={form.link} placeholder="https://..." />
				</div>

				<div class="grid grid-cols-2 gap-3">
					<div class="form-control">
						<label class="label"><span class="label-text">Cost (Cash)</span></label>
						<input type="number" class="input input-bordered w-full" bind:value={form.cost_cash} step="0.01" />
					</div>
					<div class="form-control">
						<label class="label"><span class="label-text">Cost (Points)</span></label>
						<input type="number" class="input input-bordered w-full" bind:value={form.cost_points} />
					</div>
				</div>
			</div>

			<div class="modal-action flex justify-between">
				<div>
					{#if isEdit}
						{#if confirmDelete}
							<div class="flex gap-2">
								<button type="button" class="btn btn-error btn-sm" onclick={doDelete} disabled={deleting}>
									{#if deleting}<span class="loading loading-spinner loading-xs"></span>{/if}
									Confirm Delete
								</button>
								<button type="button" class="btn btn-ghost btn-sm" onclick={() => confirmDelete = false}>Cancel</button>
							</div>
						{:else}
							<button type="button" class="btn btn-ghost btn-sm text-error" onclick={() => confirmDelete = true}>Delete</button>
						{/if}
					{/if}
				</div>
				<div class="flex gap-2">
					<button type="button" class="btn btn-ghost" onclick={close}>Cancel</button>
					<button type="submit" class="btn btn-primary" disabled={saving}>
						{#if saving}<span class="loading loading-spinner loading-sm"></span>{/if}
						{isEdit ? 'Save' : 'Create'}
					</button>
				</div>
			</div>
		</form>
	</div>
	<form method="dialog" class="modal-backdrop"><button>close</button></form>
</dialog>
