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

	let {
		lodging = null,
		tripId,
		tripStart = '',
		tripEnd = '',
		onSave,
		onDelete,
		onClose
	}: {
		lodging: Lodging | null;
		tripId: string;
		tripStart?: string;
		tripEnd?: string;
		onSave: (l: 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 form = $state({
		name: '', type: 'hotel', location: '', check_in: '', check_out: '',
		timezone: '', reservation_number: '', description: '', link: '',
		cost_points: 0, cost_cash: 0, place_id: ''
	});

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

	$effect(() => {
		if (lodging) {
			form = {
				name: lodging.name || '', type: lodging.type || 'hotel',
				location: lodging.location || '', check_in: lodging.check_in || '',
				check_out: lodging.check_out || '', timezone: lodging.timezone || '',
				reservation_number: lodging.reservation_number || '',
				description: lodging.description || '', link: lodging.link || '',
				cost_points: lodging.cost_points || 0, cost_cash: lodging.cost_cash || 0,
				place_id: lodging.place_id || ''
			};
		}
		modal?.showModal();
	});

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

	async function doDelete() {
		if (!lodging?.id) return;
		deleting = true;
		try {
			await post('/api/lodging/delete', { id: lodging.id });
			onDelete(lodging.id);
		} catch (e) { console.error('Failed to delete:', e); }
		finally { deleting = 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-secondary/15">
				<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 text-secondary" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
					<path d="M3 14h18v7H3z"/><path d="M3 7v7"/><path d="M21 7v7"/><path d="M3 7l9-4 9 4"/>
				</svg>
			</div>
			{isEdit ? 'Edit Lodging' : 'New Lodging'}
		</h3>

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

		<form onsubmit={(e) => { e.preventDefault(); save(); }}>
			<div class="space-y-3">
				<div class="grid grid-cols-3 gap-3">
					<div class="form-control col-span-2">
						<label class="label"><span class="label-text">Name</span></label>
						<PlacesAutocomplete
							bind:value={form.name}
							placeholder="Search hotels..."
							onSelect={(details) => {
								form.location = details.address || form.location;
								form.place_id = details.place_id || form.place_id;
							}}
						/>
					</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="hotel">Hotel</option>
							<option value="airbnb">Airbnb</option>
							<option value="hostel">Hostel</option>
							<option value="resort">Resort</option>
							<option value="camping">Camping</option>
						</select>
					</div>
				</div>

				<div class="form-control">
					<label class="label"><span class="label-text">Location / Address</span></label>
					<input type="text" class="input input-bordered w-full" bind:value={form.location} />
				</div>

				<div class="grid grid-cols-2 gap-3">
					<div class="form-control">
						<label class="label"><span class="label-text">Check-in</span></label>
						<input type="datetime-local" class="input input-bordered w-full" bind:value={form.check_in} />
					</div>
					<div class="form-control">
						<label class="label"><span class="label-text">Check-out</span></label>
						<input type="datetime-local" class="input input-bordered w-full" bind:value={form.check_out} />
					</div>
				</div>

				<div class="form-control">
					<label class="label"><span class="label-text">Confirmation / Reservation #</span></label>
					<input type="text" class="input input-bordered w-full" bind:value={form.reservation_number} />
				</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 || !form.name.trim()}>
						{#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>
