<script lang="ts">
	import type { SessionType, SessionNote } from './types';
	import { getSessionColorClasses, formatDateTime } from './types';

	interface Props {
		sessionType: SessionType;
		notes: SessionNote[];
		isActive: boolean;
		getTeamMemberName: (id: string | null | undefined) => string;
		onAddNote?: (content: string, internal: boolean) => Promise<void>;
		onUpdateNote?: (noteId: string, content: string, internal: boolean) => Promise<void>;
		onDeleteNote?: (noteId: string) => Promise<void>;
	}

	const {
		sessionType,
		notes,
		isActive,
		getTeamMemberName,
		onAddNote,
		onUpdateNote,
		onDeleteNote
	}: Props = $props();

	const colors = $derived(getSessionColorClasses(sessionType));

	// Form state
	let newNoteContent = $state('');
	let newNoteInternal = $state(false);
	let isAdding = $state(false);

	// Edit state
	let editingNoteId = $state<string | null>(null);
	let editContent = $state('');
	let editInternal = $state(false);
	let isUpdating = $state(false);

	// Delete state
	let deletingNoteId = $state<string | null>(null);

	async function handleAddNote() {
		if (!newNoteContent.trim() || !onAddNote) return;

		isAdding = true;
		try {
			await onAddNote(newNoteContent.trim(), newNoteInternal);
			newNoteContent = '';
			newNoteInternal = false;
		} finally {
			isAdding = false;
		}
	}

	function startEditing(note: SessionNote) {
		editingNoteId = note.id;
		editContent = note.content;
		editInternal = note.internal;
	}

	function cancelEditing() {
		editingNoteId = null;
		editContent = '';
		editInternal = false;
	}

	async function handleUpdateNote() {
		if (!editingNoteId || !editContent.trim() || !onUpdateNote) return;

		isUpdating = true;
		try {
			await onUpdateNote(editingNoteId, editContent.trim(), editInternal);
			cancelEditing();
		} finally {
			isUpdating = false;
		}
	}

	async function handleDeleteNote(noteId: string) {
		if (!onDeleteNote) return;

		deletingNoteId = noteId;
		try {
			await onDeleteNote(noteId);
		} finally {
			deletingNoteId = null;
		}
	}
</script>

<div class="space-y-4">
	<!-- Add Note Form (only for active sessions) -->
	{#if isActive && onAddNote}
		<div
			class="rounded-lg border border-gray-200 bg-white p-4 dark:border-gray-700 dark:bg-gray-800"
		>
			<label class="block">
				<span class="sr-only">Add a note</span>
				<textarea
					class="w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-sm text-gray-900 placeholder-gray-400 focus:border-transparent focus:ring-2 focus:outline-none dark:border-gray-600 dark:bg-gray-700 dark:text-gray-100 dark:placeholder-gray-500 {colors.ring}"
					rows="3"
					placeholder="Add a note..."
					disabled={isAdding}
					oninput={(e) => (newNoteContent = e.currentTarget.value)}>{newNoteContent}</textarea
				>
			</label>

			<div class="mt-3 flex items-center justify-between">
				<label class="flex items-center gap-2 text-sm text-gray-600 dark:text-gray-400">
					<input
						type="checkbox"
						class="rounded border-gray-300 text-gray-600 focus:ring-gray-500 dark:border-gray-600 dark:bg-gray-700"
						checked={newNoteInternal}
						onchange={(e) => (newNoteInternal = e.currentTarget.checked)}
						disabled={isAdding}
					/>
					<span>Internal only</span>
				</label>

				<button
					type="button"
					class="inline-flex items-center gap-1.5 rounded-lg px-4 py-2 text-sm font-medium text-white transition-colors hover:opacity-90 focus:ring-2 focus:ring-offset-2 focus:outline-none disabled:cursor-not-allowed disabled:opacity-50 {colors.bg} {colors.ring}"
					onclick={handleAddNote}
					disabled={isAdding || !newNoteContent.trim()}
				>
					{#if isAdding}
						<svg class="h-4 w-4 animate-spin" fill="none" viewBox="0 0 24 24">
							<circle
								class="opacity-25"
								cx="12"
								cy="12"
								r="10"
								stroke="currentColor"
								stroke-width="4"
							></circle>
							<path
								class="opacity-75"
								fill="currentColor"
								d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
							></path>
						</svg>
					{:else}
						<svg class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
							<path
								stroke-linecap="round"
								stroke-linejoin="round"
								stroke-width="2"
								d="M12 4v16m8-8H4"
							></path>
						</svg>
					{/if}
					<span>Add Note</span>
				</button>
			</div>
		</div>
	{/if}

	<!-- Notes List -->
	{#if notes.length === 0}
		<div class="py-8 text-center">
			<svg
				class="mx-auto h-12 w-12 text-gray-300 dark:text-gray-600"
				fill="none"
				viewBox="0 0 24 24"
				stroke="currentColor"
			>
				<path
					stroke-linecap="round"
					stroke-linejoin="round"
					stroke-width="1.5"
					d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"
				></path>
			</svg>
			<p class="mt-2 text-sm text-gray-500 dark:text-gray-400">No notes yet</p>
		</div>
	{:else}
		<div class="space-y-3">
			{#each notes as note (note.id)}
				<div
					class="rounded-lg border bg-white p-4 dark:bg-gray-800 {note.internal
						? 'border-yellow-200 bg-yellow-50/50 dark:border-yellow-800/50 dark:bg-yellow-900/10'
						: 'border-gray-200 dark:border-gray-700'}"
				>
					{#if editingNoteId === note.id}
						<!-- Edit Mode -->
						<label class="block">
							<span class="sr-only">Edit note</span>
							<textarea
								class="w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-sm text-gray-900 placeholder-gray-400 focus:border-transparent focus:ring-2 focus:outline-none dark:border-gray-600 dark:bg-gray-700 dark:text-gray-100 {colors.ring}"
								rows="3"
								disabled={isUpdating}
								oninput={(e) => (editContent = e.currentTarget.value)}>{editContent}</textarea
							>
						</label>

						<div class="mt-3 flex items-center justify-between">
							<label class="flex items-center gap-2 text-sm text-gray-600 dark:text-gray-400">
								<input
									type="checkbox"
									class="rounded border-gray-300 text-gray-600 focus:ring-gray-500 dark:border-gray-600 dark:bg-gray-700"
									checked={editInternal}
									onchange={(e) => (editInternal = e.currentTarget.checked)}
									disabled={isUpdating}
								/>
								<span>Internal only</span>
							</label>

							<div class="flex gap-2">
								<button
									type="button"
									class="rounded-lg px-3 py-1.5 text-sm text-gray-600 hover:bg-gray-100 dark:text-gray-400 dark:hover:bg-gray-700"
									onclick={cancelEditing}
									disabled={isUpdating}
								>
									Cancel
								</button>
								<button
									type="button"
									class="inline-flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-sm font-medium text-white {colors.bg}"
									onclick={handleUpdateNote}
									disabled={isUpdating || !editContent.trim()}
								>
									{#if isUpdating}
										<svg class="h-4 w-4 animate-spin" fill="none" viewBox="0 0 24 24">
											<circle
												class="opacity-25"
												cx="12"
												cy="12"
												r="10"
												stroke="currentColor"
												stroke-width="4"
											></circle>
											<path
												class="opacity-75"
												fill="currentColor"
												d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
											></path>
										</svg>
									{/if}
									<span>Save</span>
								</button>
							</div>
						</div>
					{:else}
						<!-- View Mode -->
						<div class="flex items-start justify-between gap-4">
							<div class="flex-1">
								<div class="flex items-center gap-2 text-xs text-gray-500 dark:text-gray-400">
									<span>{getTeamMemberName(note.authorId)}</span>
									<span class="text-gray-400 dark:text-gray-600">|</span>
									<span>{formatDateTime(note.createdAt)}</span>
									{#if note.internal}
										<span
											class="rounded-full bg-yellow-100 px-1.5 py-0.5 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-400"
										>
											Internal
										</span>
									{/if}
								</div>
								<p class="mt-1 text-sm whitespace-pre-wrap text-gray-700 dark:text-gray-300">
									{note.content}
								</p>
							</div>

							{#if isActive && (onUpdateNote || onDeleteNote)}
								<div class="flex shrink-0 gap-1">
									{#if onUpdateNote}
										<button
											type="button"
											class="rounded p-1 text-gray-400 hover:bg-gray-100 hover:text-gray-600 dark:hover:bg-gray-700 dark:hover:text-gray-300"
											onclick={() => startEditing(note)}
											aria-label="Edit note"
										>
											<svg class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
												<path
													stroke-linecap="round"
													stroke-linejoin="round"
													stroke-width="2"
													d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"
												></path>
											</svg>
										</button>
									{/if}
									{#if onDeleteNote}
										<button
											type="button"
											class="rounded p-1 text-gray-400 hover:bg-red-50 hover:text-red-600 dark:hover:bg-red-900/20 dark:hover:text-red-400"
											onclick={() => handleDeleteNote(note.id)}
											disabled={deletingNoteId === note.id}
											aria-label="Delete note"
										>
											{#if deletingNoteId === note.id}
												<svg class="h-4 w-4 animate-spin" fill="none" viewBox="0 0 24 24">
													<circle
														class="opacity-25"
														cx="12"
														cy="12"
														r="10"
														stroke="currentColor"
														stroke-width="4"
													></circle>
													<path
														class="opacity-75"
														fill="currentColor"
														d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
													></path>
												</svg>
											{:else}
												<svg class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
													<path
														stroke-linecap="round"
														stroke-linejoin="round"
														stroke-width="2"
														d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"
													></path>
												</svg>
											{/if}
										</button>
									{/if}
								</div>
							{/if}
						</div>
					{/if}
				</div>
			{/each}
		</div>
	{/if}
</div>
