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

	let {
		location = null,
		tripId,
		tripStart = '',
		tripEnd = '',
		onSave,
		onDelete,
		onClose
	}: {
		location: Location | null;
		tripId: string;
		tripStart?: string;
		tripEnd?: string;
		onSave: (loc: 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: '',
		description: '',
		category: '',
		visit_date: '',
		start_time: '',
		end_time: '',
		link: '',
		cost_points: 0,
		cost_cash: 0,
		address: '',
		place_id: '',
		hike_distance: '',
		hike_difficulty: '',
		hike_time: ''
	});

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

	$effect(() => {
		if (location) {
			form = {
				name: location.name || '',
				description: location.description || '',
				category: location.category || '',
				visit_date: location.visit_date || '',
				start_time: location.start_time || '',
				end_time: location.end_time || '',
				link: location.link || '',
				cost_points: location.cost_points || 0,
				cost_cash: location.cost_cash || 0,
				address: location.address || '',
				place_id: location.place_id || '',
				hike_distance: location.hike_distance || '',
				hike_difficulty: location.hike_difficulty || '',
				hike_time: location.hike_time || ''
			};
		}
		modal?.showModal();
	});

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

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

	function close() {
		modal?.close();
		onClose();
	}

	function handleModalRefresh() {
		// Reload the trip to get updated images
		onSave({});
	}

	function stripHtml(html: string): string {
		if (!html) return '';
		const div = document.createElement('div');
		div.innerHTML = html;
		return div.textContent || '';
	}
</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-accent/15">
				<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 text-accent" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
					<path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z"/><circle cx="12" cy="10" r="3"/>
				</svg>
			</div>
			{isEdit ? 'Edit Activity' : 'New Activity'}
		</h3>

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

		<form onsubmit={(e) => { e.preventDefault(); save(); }}>
			<div class="space-y-3">
				<div class="form-control">
					<label class="label"><span class="label-text">Name</span></label>
					<PlacesAutocomplete
						bind:value={form.name}
						placeholder="Search for a place..."
						onSelect={(details) => {
							form.address = details.address || form.address;
							form.place_id = details.place_id || form.place_id;
							if (details.category) form.category = details.category;
						}}
					/>
				</div>

				<div class="grid grid-cols-2 gap-3">
					<div class="form-control">
						<label class="label"><span class="label-text">Category</span></label>
						<select class="select select-bordered w-full" bind:value={form.category}>
							<option value="">None</option>
							<option value="attraction">Attraction</option>
							<option value="restaurant">Restaurant</option>
							<option value="cafe">Cafe</option>
							<option value="bar">Bar</option>
							<option value="hike">Hike</option>
							<option value="shopping">Shopping</option>
							<option value="beach">Beach</option>
						</select>
					</div>
					<div class="form-control">
						<label class="label"><span class="label-text">Date</span></label>
						<input type="date" class="input input-bordered w-full" bind:value={form.visit_date} />
					</div>
				</div>

				<div class="grid grid-cols-2 gap-3">
					<div class="form-control">
						<label class="label"><span class="label-text">Start Time</span></label>
						<input type="datetime-local" class="input input-bordered w-full" bind:value={form.start_time} />
					</div>
					<div class="form-control">
						<label class="label"><span class="label-text">End Time</span></label>
						<input type="datetime-local" class="input input-bordered w-full" bind:value={form.end_time} />
					</div>
				</div>

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

				<div class="form-control">
					<label class="label"><span class="label-text">Address</span></label>
					<input type="text" class="input input-bordered w-full" bind:value={form.address} />
				</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>

				{#if form.category === 'hike'}
					<div class="grid grid-cols-3 gap-3">
						<div class="form-control">
							<label class="label"><span class="label-text">Distance</span></label>
							<input type="text" class="input input-bordered w-full" bind:value={form.hike_distance} placeholder="5.2 mi" />
						</div>
						<div class="form-control">
							<label class="label"><span class="label-text">Difficulty</span></label>
							<input type="text" class="input input-bordered w-full" bind:value={form.hike_difficulty} placeholder="Moderate" />
						</div>
						<div class="form-control">
							<label class="label"><span class="label-text">Time</span></label>
							<input type="text" class="input input-bordered w-full" bind:value={form.hike_time} placeholder="3h" />
						</div>
					</div>
				{/if}
			</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>
