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

	let {
		note = null,
		tripId,
		onSave,
		onDelete,
		onClose
	}: {
		note: Note | null;
		tripId: string;
		onSave: (n: 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: '', content: '', date: '' });
	let isEdit = $derived(!!note?.id);

	$effect(() => {
		if (note) {
			form = {
				name: note.name || '',
				content: note.content || '',
				date: note.date || ''
			};
		}
		modal?.showModal();
	});

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

	async function doDelete() {
		if (!note?.id) return;
		deleting = true;
		try {
			await post('/api/note/delete', { id: note.id });
			onDelete(note.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-warning/15">
				<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 text-warning" 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>
			</div>
			{isEdit ? 'Edit Note' : 'New Note'}
		</h3>

		<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">Title</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">Date</span></label>
						<input type="date" class="input input-bordered w-full" bind:value={form.date} />
					</div>
				</div>

				<div class="form-control">
					<label class="label"><span class="label-text">Content</span></label>
					<textarea class="textarea textarea-bordered w-full" rows="8" bind:value={form.content}></textarea>
				</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>
