<script lang="ts">
	import { post, api } from '$lib/api/client';

	let {
		tripId,
		tripStart = '',
		tripEnd = '',
		onParsed,
		onClose
	}: {
		tripId: string;
		tripStart?: string;
		tripEnd?: string;
		onParsed: () => void;
		onClose: () => void;
	} = $props();

	let modal = $state<HTMLDialogElement | null>(null);
	let textInput = $state('');
	let parsing = $state(false);
	let saving = $state(false);
	let result = $state<any>(null);
	let error = $state('');
	let fileInput = $state<HTMLInputElement | null>(null);

	$effect(() => { modal?.showModal(); });

	async function parseText() {
		if (!textInput.trim()) return;
		parsing = true;
		error = '';
		result = null;
		try {
			result = await post('/api/parse', {
				text: textInput,
				trip_start: tripStart,
				trip_end: tripEnd
			});
			if (result.error) {
				error = result.error;
				result = null;
			}
		} catch (e) {
			error = 'Parse failed';
		} finally {
			parsing = false;
		}
	}

	async function parseFile(e: Event) {
		const input = e.target as HTMLInputElement;
		if (!input.files?.length) return;

		parsing = true;
		error = '';
		result = null;

		const formData = new FormData();
		formData.append('file', input.files[0]);
		formData.append('text', textInput || '');
		if (tripStart) formData.append('trip_start', tripStart);
		if (tripEnd) formData.append('trip_end', tripEnd);

		try {
			const token = localStorage.getItem('api_token') || '';
			const res = await fetch('/api/parse', {
				method: 'POST',
				headers: { 'Authorization': `Bearer ${token}` },
				body: formData
			});
			result = await res.json();
			if (result.error) {
				error = result.error;
				result = null;
			}
		} catch {
			error = 'Parse failed';
		} finally {
			parsing = false;
			input.value = '';
		}
	}

	async function resolvePlaceId(name: string, address: string): Promise<{ place_id?: string; address?: string }> {
		try {
			const query = address ? `${name} ${address}` : name;
			const acData = await post<{ predictions: Array<{ place_id: string; address: string }> }>(
				'/api/places/autocomplete', { query }
			);
			if (acData.predictions?.length > 0) {
				const placeId = acData.predictions[0].place_id;
				// Get full details for coordinates
				const token = localStorage.getItem('api_token') || '';
				const res = await fetch(`/api/places/details?place_id=${encodeURIComponent(placeId)}`, {
					headers: { 'Authorization': `Bearer ${token}` }
				});
				const details = await res.json();
				return {
					place_id: placeId,
					address: details.address || acData.predictions[0].address || address
				};
			}
		} catch { /* ignore */ }
		return {};
	}

	async function saveResult() {
		if (!result?.data) return;
		saving = true;
		try {
			const data = { ...result.data, trip_id: tripId };
			const type = result.type;

			// Resolve place_id for locations and lodging
			if (type === 'location' || type === 'activity' || type === 'hotel' || type === 'lodging') {
				const place = await resolvePlaceId(data.name || '', data.address || data.location || '');
				if (place.place_id) data.place_id = place.place_id;
				if (place.address) {
					if (type === 'hotel' || type === 'lodging') {
						data.location = place.address;
					} else {
						data.address = place.address;
					}
				}
			}

			// Resolve from/to place_ids for transport
			if (type === 'flight' || type === 'transportation' || type === 'car' || type === 'train') {
				if (data.from_location) {
					const from = await resolvePlaceId(data.from_location, '');
					if (from.place_id) data.from_place_id = from.place_id;
				}
				if (data.to_location) {
					const to = await resolvePlaceId(data.to_location, '');
					if (to.place_id) data.to_place_id = to.place_id;
				}
			}

			if (type === 'flight' || type === 'transportation' || type === 'car' || type === 'train') {
				await post('/api/transportation', data);
			} else if (type === 'hotel' || type === 'lodging') {
				await post('/api/lodging', data);
			} else if (type === 'location' || type === 'activity') {
				await post('/api/location', data);
			} else {
				// Default to note
				await post('/api/note', {
					trip_id: tripId,
					name: data.name || 'Parsed Note',
					content: JSON.stringify(data, null, 2),
					date: data.date?.split('T')[0] || ''
				});
			}
			onParsed();
		} catch (e) {
			console.error('Save failed:', e);
			error = 'Failed to save';
		} finally {
			saving = false;
		}
	}

	function typeLabel(type: string): string {
		switch (type) {
			case 'flight': return 'Flight';
			case 'hotel': case 'lodging': return 'Hotel';
			case 'location': case 'activity': return 'Activity';
			case 'car': return 'Car Rental';
			case 'train': return 'Train';
			default: return type || 'Unknown';
		}
	}

	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-primary/15">
				<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 text-primary" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
					<polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/>
				</svg>
			</div>
			AI Parse
		</h3>

		{#if !result}
			<!-- Input -->
			<div class="space-y-3">
				<div class="form-control">
					<label class="label"><span class="label-text">Paste confirmation email, booking text, or details</span></label>
					<textarea
						class="textarea textarea-bordered w-full"
						rows="6"
						placeholder="Paste flight confirmation, hotel booking, activity details..."
						bind:value={textInput}
					></textarea>
				</div>

				<div class="flex gap-2">
					<button type="button" class="btn btn-primary flex-1" onclick={parseText} disabled={parsing || !textInput.trim()}>
						{#if parsing}
							<span class="loading loading-spinner loading-sm"></span>
							Parsing...
						{:else}
							Parse Text
						{/if}
					</button>

					<label class="btn btn-outline flex-1 cursor-pointer">
						{#if parsing}
							<span class="loading loading-spinner loading-sm"></span>
						{:else}
							<svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
								<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><path d="M14 2v6h6"/>
							</svg>
							Upload PDF / Image
						{/if}
						<input type="file" accept="image/*,.pdf" class="hidden" bind:this={fileInput} onchange={parseFile} disabled={parsing} />
					</label>
				</div>

				{#if error}
					<div class="alert alert-error text-sm py-2"><span>{error}</span></div>
				{/if}
			</div>
		{:else}
			<!-- Result preview -->
			<div class="space-y-4">
				<div class="flex items-center gap-2">
					<span class="badge badge-primary">{typeLabel(result.type)}</span>
					{#if result.confidence}
						<span class="text-xs text-base-content/40">{Math.round(result.confidence * 100)}% confident</span>
					{/if}
				</div>

				<div class="bg-base-200 rounded-lg p-4 space-y-2">
					{#each Object.entries(result.data || {}) as [key, value]}
						{#if value && key !== 'type'}
							<div class="flex justify-between text-sm">
								<span class="text-base-content/50 capitalize">{key.replace(/_/g, ' ')}</span>
								<span class="text-base-content font-medium text-right max-w-xs truncate">{value}</span>
							</div>
						{/if}
					{/each}
				</div>

				{#if error}
					<div class="alert alert-error text-sm py-2"><span>{error}</span></div>
				{/if}

				<div class="flex gap-2">
					<button type="button" class="btn btn-ghost flex-1" onclick={() => { result = null; error = ''; }}>
						Back
					</button>
					<button type="button" class="btn btn-primary flex-1" onclick={saveResult} disabled={saving}>
						{#if saving}
							<span class="loading loading-spinner loading-sm"></span>
						{/if}
						Save to Trip
					</button>
				</div>
			</div>
		{/if}
	</div>
	<form method="dialog" class="modal-backdrop"><button>close</button></form>
</dialog>
