<script lang="ts">
	import type { SessionNote } from './types';
	import { formatDateTime } from './types';
	import IconSpinner from '$lib/components/icons/IconSpinner.svelte';

	interface Props {
		notes: SessionNote[];
		isActive: boolean;
		getTeamMemberName?: (id: string | null | undefined) => string;
		onAdd?: (content: string, internal: boolean) => Promise<void>;
		onUpdate?: (noteId: string, content: string, internal: boolean) => Promise<void>;
		onDelete?: (noteId: string) => Promise<void>;
	}

	let {
		notes,
		isActive,
		getTeamMemberName = () => 'Unknown',
		onAdd,
		onUpdate,
		onDelete
	}: Props = $props();

	// Add note form state
	let showAddForm = $state(false);
	let newNoteContent = $state('');
	let newNoteInternal = $state(true);
	let isAdding = $state(false);

	// Edit state
	let editingId = $state<string | null>(null);
	let editContent = $state('');
	let editInternal = $state(true);
	let isEditing = $state(false);

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

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

		isAdding = true;
		try {
			await onAdd(newNoteContent.trim(), newNoteInternal);
			newNoteContent = '';
			newNoteInternal = true;
			showAddForm = false;
		} catch (err) {
			console.error('Failed to add note:', err);
		} finally {
			isAdding = false;
		}
	}

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

	function cancelEdit() {
		editingId = null;
		editContent = '';
		editInternal = true;
	}

	async function handleUpdateNote() {
		if (!editingId || !editContent.trim() || !onUpdate) return;

		isEditing = true;
		try {
			await onUpdate(editingId, editContent.trim(), editInternal);
			cancelEdit();
		} catch (err) {
			console.error('Failed to update note:', err);
		} finally {
			isEditing = false;
		}
	}

	async function handleDeleteNote(noteId: string) {
		if (!onDelete || !confirm('Are you sure you want to delete this note?')) return;

		deletingId = noteId;
		try {
			await onDelete(noteId);
		} catch (err) {
			console.error('Failed to delete note:', err);
		} finally {
			deletingId = null;
		}
	}

	// Sort notes by creation date (newest first)
	let sortedNotes = $derived(
		[...notes].sort((a, b) => {
			const dateA = new Date(a.createdAt).getTime();
			const dateB = new Date(b.createdAt).getTime();
			return dateB - dateA;
		})
	);
</script>

<div class="space-y-4">
	<!-- Add Note Button/Form -->
	{#if isActive}
		{#if showAddForm}
			<div class="card-padded border-2 border-primary-500/30 bg-primary-500/5">
				<h3 class="mb-4 font-medium text-theme">Add Note</h3>

				<div class="space-y-4">
					<div>
						<textarea
							bind:value={newNoteContent}
							placeholder="Write your note..."
							rows="4"
							class="w-full rounded-lg border border-theme bg-theme-card px-3 py-2 text-theme placeholder:text-theme-muted focus:border-primary-500 focus:ring-1 focus:ring-primary-500 focus:outline-none"
						></textarea>
					</div>

					<label class="flex items-center gap-2">
						<input
							type="checkbox"
							bind:checked={newNoteInternal}
							class="h-4 w-4 rounded border-input text-primary-600 focus:ring-primary-500"
						/>
						<span class="text-sm text-theme">Internal only (not visible to customer)</span>
					</label>

					<div class="flex gap-3">
						<button
							type="button"
							onclick={() => {
								showAddForm = false;
								newNoteContent = '';
							}}
							disabled={isAdding}
							class="btn-ghost flex-1 disabled:opacity-50"
						>
							Cancel
						</button>
						<button
							type="button"
							onclick={handleAddNote}
							disabled={!newNoteContent.trim() || isAdding}
							class="btn-primary flex-1 disabled:opacity-50"
						>
							{isAdding ? 'Adding...' : 'Add Note'}
						</button>
					</div>
				</div>
			</div>
		{:else}
			<button
				type="button"
				onclick={() => (showAddForm = true)}
				class="flex w-full items-center justify-center gap-2 rounded-lg border-2 border-dashed border-theme p-4 text-theme-muted transition-colors hover:border-primary-500 hover:text-primary-500"
			>
				<svg class="h-5 w-5" style="fill: none" stroke="currentColor" viewBox="0 0 24 24">
					<path
						stroke-linecap="round"
						stroke-linejoin="round"
						stroke-width="2"
						d="M12 4v16m8-8H4"
					/>
				</svg>
				Add Note
			</button>
		{/if}
	{/if}

	<!-- Notes List -->
	{#if sortedNotes.length > 0}
		<div class="space-y-3">
			{#each sortedNotes as note (note.id)}
				<div class="card-padded">
					{#if editingId === note.id}
						<!-- Edit Mode -->
						<div class="space-y-4">
							<textarea
								bind:value={editContent}
								rows="4"
								class="w-full rounded-lg border border-theme bg-theme px-3 py-2 text-theme focus:border-primary-500 focus:ring-1 focus:ring-primary-500 focus:outline-none"
							></textarea>

							<label class="flex items-center gap-2">
								<input
									type="checkbox"
									bind:checked={editInternal}
									class="h-4 w-4 rounded border-input text-primary-600 focus:ring-primary-500"
								/>
								<span class="text-sm text-theme">Internal only</span>
							</label>

							<div class="flex gap-3">
								<button
									type="button"
									onclick={cancelEdit}
									disabled={isEditing}
									class="btn-ghost flex-1 disabled:opacity-50"
								>
									Cancel
								</button>
								<button
									type="button"
									onclick={handleUpdateNote}
									disabled={!editContent.trim() || isEditing}
									class="btn-primary flex-1 disabled:opacity-50"
								>
									{isEditing ? 'Saving...' : 'Save'}
								</button>
							</div>
						</div>
					{:else}
						<!-- View Mode -->
						<div class="flex items-start gap-3">
							<div class="min-w-0 flex-1">
								<div class="mb-2 flex items-center gap-2">
									{#if note.authorId}
										<span class="text-sm font-medium text-theme">
											{getTeamMemberName(note.authorId)}
										</span>
									{/if}
									{#if note.internal}
										<span class="badge-warning">Internal</span>
									{/if}
								</div>

								<p class="whitespace-pre-wrap text-theme">{note.content}</p>

								<p class="mt-2 text-xs text-theme-muted">
									{formatDateTime(note.createdAt)}
									{#if note.updatedAt && note.updatedAt !== note.createdAt}
										<span class="italic"> (edited)</span>
									{/if}
								</p>
							</div>

							{#if isActive}
								<div class="flex flex-shrink-0 gap-1">
									<button
										type="button"
										onclick={() => startEdit(note)}
										class="rounded p-1.5 text-theme-muted hover:bg-primary-50 hover:text-primary-500 dark:hover:bg-primary-900/20"
										title="Edit note"
									>
										<svg
											class="h-4 w-4"
											style="fill: none"
											stroke="currentColor"
											viewBox="0 0 24 24"
										>
											<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"
											/>
										</svg>
									</button>
									<button
										type="button"
										onclick={() => handleDeleteNote(note.id)}
										disabled={deletingId === note.id}
										class="rounded p-1.5 text-theme-muted hover:bg-error-50 hover:text-error-500 disabled:opacity-50 dark:hover:bg-error-900/20"
										title="Delete note"
									>
										{#if deletingId === note.id}
											<IconSpinner class="h-4 w-4" />
										{:else}
											<svg
												class="h-4 w-4"
												style="fill: none"
												stroke="currentColor"
												viewBox="0 0 24 24"
											>
												<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"
												/>
											</svg>
										{/if}
									</button>
								</div>
							{/if}
						</div>
					{/if}
				</div>
			{/each}
		</div>
	{:else}
		<!-- Empty State -->
		<div class="empty-state">
			<svg class="empty-state-icon" style="fill: none" stroke="currentColor" viewBox="0 0 24 24">
				<path
					stroke-linecap="round"
					stroke-linejoin="round"
					stroke-width="1.5"
					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"
				/>
			</svg>
			<h2 class="empty-state-title">No Notes Yet</h2>
			<p class="empty-state-text">
				{#if isActive}
					Add notes to document important information.
				{:else}
					No notes were added to this session.
				{/if}
			</p>
		</div>
	{/if}
</div>
