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

	let {
		trip,
		onSave,
		onClose
	}: {
		trip: Trip;
		onSave: () => void;
		onClose: () => void;
	} = $props();

	let modal = $state<HTMLDialogElement | null>(null);
	let saving = $state(false);
	let deleting = $state(false);
	let confirmDelete = $state(false);
	let sharing = $state(false);
	let shareUrl = $state('');
	let copied = $state(false);

	let form = $state({
		name: '', description: '', start_date: '', end_date: ''
	});

	let tripImages = $derived((trip as any)?.images || []);

	$effect(() => {
		if (trip.share_token) {
			shareUrl = `${window.location.origin}/view/${trip.share_token}`;
		} else {
			shareUrl = '';
		}
		form = {
			name: trip.name || '',
			description: trip.description || '',
			start_date: trip.start_date || '',
			end_date: trip.end_date || ''
		};
		modal?.showModal();
	});

	async function save() {
		saving = true;
		try {
			await post('/api/trip/update', { id: trip.id, ...form });
			onSave();
		} catch (e) {
			console.error('Failed to update trip:', e);
		} finally {
			saving = false;
		}
	}

	async function doDelete() {
		deleting = true;
		try {
			await post('/api/trip/delete', { id: trip.id });
			goto('/');
		} catch (e) {
			console.error('Failed to delete trip:', e);
		} finally {
			deleting = false;
		}
	}

	async function toggleShare() {
		sharing = true;
		try {
			if (shareUrl) {
				await post('/api/share/delete', { trip_id: trip.id });
				shareUrl = '';
			} else {
				const result = await post<{ share_token: string }>('/api/share/create', { trip_id: trip.id });
				shareUrl = `${window.location.origin}/view/${result.share_token}`;
			}
		} catch (e) { console.error('Share failed:', e); }
		finally { sharing = false; }
	}

	async function copyShareUrl() {
		await navigator.clipboard.writeText(shareUrl);
		copied = true;
		setTimeout(() => copied = false, 2000);
	}

	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-lg 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">
					<path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/>
				</svg>
			</div>
			Edit Trip
		</h3>

		<!-- Cover Image -->
		<div class="mb-4">
			<label class="label"><span class="label-text text-sm">Cover Image</span></label>
			<ImageUpload entityType="trip" entityId={trip.id} images={tripImages} entityName={form.name} onUpload={onSave} />
		</div>

		<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>
					<input type="text" class="input input-bordered w-full" bind:value={form.name} required />
				</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="grid grid-cols-2 gap-3">
					<div class="form-control">
						<label class="label"><span class="label-text">Start Date</span></label>
						<input type="date" class="input input-bordered w-full" bind:value={form.start_date} />
					</div>
					<div class="form-control">
						<label class="label"><span class="label-text">End Date</span></label>
						<input type="date" class="input input-bordered w-full" bind:value={form.end_date} />
					</div>
				</div>

				<!-- Sharing -->
				<div class="divider text-xs text-base-content/30">Sharing</div>
				{#if shareUrl}
					<div class="flex gap-2">
						<input type="text" class="input input-bordered input-sm flex-1 text-xs" value={shareUrl} readonly />
						<button type="button" class="btn btn-sm btn-ghost" onclick={copyShareUrl}>
							{copied ? 'Copied!' : 'Copy'}
						</button>
						<button type="button" class="btn btn-sm btn-ghost text-error" onclick={toggleShare} disabled={sharing}>
							Revoke
						</button>
					</div>
				{:else}
					<button type="button" class="btn btn-sm btn-outline gap-2" onclick={toggleShare} disabled={sharing}>
						{#if sharing}<span class="loading loading-spinner loading-xs"></span>{/if}
						<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="M4 12v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8"/><polyline points="16 6 12 2 8 6"/><line x1="12" y1="2" x2="12" y2="15"/>
						</svg>
						Create Share Link
					</button>
				{/if}
			</div>

			<div class="modal-action flex justify-between">
				<div>
					{#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}
								Yes, Delete Trip
							</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 Trip</button>
					{/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}
						Save
					</button>
				</div>
			</div>
		</form>
	</div>
	<form method="dialog" class="modal-backdrop"><button>close</button></form>
</dialog>
