<script lang="ts">
	import type { SvelteSet } from 'svelte/reactivity';
	import type {
		SessionType,
		ExtendedTask,
		AreaWithCompletions,
		AreaWithTasks,
		ServiceArea,
		ProjectArea
	} from './types';
	import {
		getSessionColorClasses,
		frequencyColors,
		formatFrequency,
		isServiceTask,
		formatDateTime
	} from './types';

	interface Props {
		sessionType: SessionType;
		isActive: boolean;
		areas: (ServiceArea | ProjectArea)[];
		tasks: ExtendedTask[];
		selectedTaskIds: SvelteSet<string>;
		completedTaskIds: SvelteSet<string>;
		completedTasksByArea: AreaWithCompletions[];
		readyToSubmitByArea: AreaWithTasks[];
		availableTasksCount: number;
		submittingTaskId?: string | null;
		removingTaskId?: string | null;
		onToggleTask?: (id: string) => void;
		onSubmitTask?: (id: string) => void;
		onRemoveTask?: (id: string) => void;
		onRemoveCompletedTask?: (id: string) => void;
		onSubmitAllTasks?: () => void;
		onClearSelection?: () => void;
	}

	const {
		sessionType,
		isActive,
		areas,
		tasks,
		selectedTaskIds,
		completedTaskIds,
		completedTasksByArea,
		readyToSubmitByArea,
		availableTasksCount,
		submittingTaskId,
		removingTaskId,
		onToggleTask,
		onSubmitTask,
		onRemoveTask,
		onRemoveCompletedTask,
		onSubmitAllTasks,
		onClearSelection
	}: Props = $props();

	const colors = $derived(getSessionColorClasses(sessionType));
	const hasSelectedTasks = $derived(selectedTaskIds.size > 0);
	const hasReadyToSubmit = $derived(readyToSubmitByArea.length > 0);
	const hasCompletedTasks = $derived(completedTasksByArea.length > 0);

	// Expandable area state - prefix with section to keep them separate
	let expandedAreas = $state<Set<string>>(new Set());

	function toggleArea(section: string, areaId: string) {
		const key = `${section}:${areaId}`;
		const newSet = new Set(expandedAreas);
		if (newSet.has(key)) {
			newSet.delete(key);
		} else {
			newSet.add(key);
		}
		expandedAreas = newSet;
	}

	function isAreaExpanded(section: string, areaId: string): boolean {
		return expandedAreas.has(`${section}:${areaId}`);
	}

	// Group available tasks by area
	const availableTasksByArea = $derived(() => {
		const grouped: Map<string, { area: ServiceArea | ProjectArea; tasks: ExtendedTask[] }> =
			new Map();

		for (const task of tasks) {
			if (selectedTaskIds.has(task.id) || completedTaskIds.has(task.id)) continue;

			const area = areas.find((a) => a.id === task.areaId);
			if (!area) continue;

			if (!grouped.has(area.id)) {
				grouped.set(area.id, { area, tasks: [] });
			}
			grouped.get(area.id)!.tasks.push(task);
		}

		return Array.from(grouped.values()).sort((a, b) => a.area.order - b.area.order);
	});
</script>

<div class="space-y-6">
	<!-- Ready to Submit Section -->
	{#if hasReadyToSubmit && isActive}
		<div
			class="rounded-lg border-2 border-dashed border-green-300 bg-green-50/50 p-4 dark:border-green-700 dark:bg-green-900/10"
		>
			<div class="mb-3 flex flex-wrap items-center justify-between gap-2">
				<h4 class="font-medium text-green-800 dark:text-green-400">
					Ready to Submit ({selectedTaskIds.size})
				</h4>
				<div class="flex gap-2">
					{#if onClearSelection}
						<button
							type="button"
							class="text-sm text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200"
							onclick={onClearSelection}
						>
							Clear
						</button>
					{/if}
					{#if onSubmitAllTasks && selectedTaskIds.size > 0}
						<button
							type="button"
							class="inline-flex items-center gap-1.5 rounded-lg bg-green-600 px-3 py-1.5 text-sm font-medium text-white hover:bg-green-700"
							onclick={onSubmitAllTasks}
							disabled={!!submittingTaskId}
						>
							<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="M5 13l4 4L19 7"
								></path>
							</svg>
							<span>Submit All</span>
						</button>
					{/if}
				</div>
			</div>

			<div class="space-y-2">
				{#each readyToSubmitByArea as { area, tasks: areaTasks }}
					<div
						class="rounded-lg border border-green-200 bg-white dark:border-green-800 dark:bg-gray-800 {sessionType ===
						'service'
							? 'border-l-4 border-l-secondary-400'
							: 'border-l-4 border-l-accent-400'}"
					>
						<!-- Area Header -->
						<button
							type="button"
							onclick={() => toggleArea('ready', area.id)}
							class="flex w-full items-center gap-2 px-3 py-2 text-left"
						>
							<svg
								class="h-4 w-4 shrink-0 text-gray-500 transition-transform dark:text-gray-400 {isAreaExpanded(
									'ready',
									area.id
								)
									? 'rotate-90'
									: ''}"
								fill="none"
								stroke="currentColor"
								viewBox="0 0 24 24"
							>
								<path
									stroke-linecap="round"
									stroke-linejoin="round"
									stroke-width="2"
									d="M9 5l7 7-7 7"
								/>
							</svg>
							<span class="flex-1 text-sm font-medium text-gray-700 dark:text-gray-300"
								>{area.name}</span
							>
							<span
								class="rounded-full bg-green-100 px-2 py-0.5 text-xs font-medium text-green-700 dark:bg-green-900/50 dark:text-green-400"
							>
								{areaTasks.length}
							</span>
						</button>
						<!-- Tasks (expanded) -->
						{#if isAreaExpanded('ready', area.id)}
							<div class="space-y-1 border-t border-green-200 px-3 py-2 dark:border-green-800">
								{#each areaTasks as task (task.id)}
									<div
										class="flex flex-col gap-2 rounded-lg bg-gray-50 px-3 py-2 sm:flex-row sm:items-center sm:justify-between dark:bg-gray-700/50"
									>
										<div class="flex items-center gap-3">
											<button
												type="button"
												class="shrink-0 rounded p-1 text-gray-400 hover:bg-gray-100 hover:text-gray-600 dark:hover:bg-gray-700"
												onclick={() => onRemoveTask?.(task.id)}
												disabled={removingTaskId === task.id}
												aria-label="Remove from selection"
											>
												<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="M6 18L18 6M6 6l12 12"
													></path>
												</svg>
											</button>
											<span class="text-sm text-gray-900 dark:text-gray-100">
												{task.sessionDescription || task.scopeDescription}
											</span>
										</div>
										<div class="ml-8 flex items-center gap-2 sm:ml-0">
											{#if isServiceTask(task) && task.frequency}
												<span
													class="rounded-full px-2 py-0.5 text-xs font-medium {frequencyColors[
														task.frequency
													] ?? frequencyColors['WEEKLY']}"
												>
													{formatFrequency(task.frequency)}
												</span>
											{/if}
											{#if onSubmitTask}
												<button
													type="button"
													class="inline-flex items-center gap-1 rounded bg-green-600 px-2 py-1 text-xs font-medium text-white hover:bg-green-700"
													onclick={() => onSubmitTask(task.id)}
													disabled={submittingTaskId === task.id}
												>
													{#if submittingTaskId === task.id}
														<svg class="h-3 w-3 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-3 w-3"
															fill="none"
															viewBox="0 0 24 24"
															stroke="currentColor"
														>
															<path
																stroke-linecap="round"
																stroke-linejoin="round"
																stroke-width="2"
																d="M5 13l4 4L19 7"
															></path>
														</svg>
													{/if}
													<span>Submit</span>
												</button>
											{/if}
										</div>
									</div>
								{/each}
							</div>
						{/if}
					</div>
				{/each}
			</div>
		</div>
	{/if}

	<!-- Completed Tasks Section -->
	{#if hasCompletedTasks}
		<div>
			<h4 class="mb-3 font-medium text-gray-900 dark:text-gray-100">
				Completed ({completedTaskIds.size})
			</h4>
			<div class="space-y-2">
				{#each completedTasksByArea as { area, completions }}
					<div
						class="rounded-lg border border-gray-200 bg-white dark:border-gray-700 dark:bg-gray-800 {sessionType ===
						'service'
							? 'border-l-4 border-l-secondary-400'
							: 'border-l-4 border-l-accent-400'}"
					>
						<!-- Area Header -->
						<button
							type="button"
							onclick={() => toggleArea('completed', area.id)}
							class="flex w-full items-center gap-2 px-3 py-2 text-left"
						>
							<svg
								class="h-4 w-4 shrink-0 text-gray-500 transition-transform dark:text-gray-400 {isAreaExpanded(
									'completed',
									area.id
								)
									? 'rotate-90'
									: ''}"
								fill="none"
								stroke="currentColor"
								viewBox="0 0 24 24"
							>
								<path
									stroke-linecap="round"
									stroke-linejoin="round"
									stroke-width="2"
									d="M9 5l7 7-7 7"
								/>
							</svg>
							<span class="flex-1 text-sm font-medium text-gray-700 dark:text-gray-300"
								>{area.name}</span
							>
							<span
								class="rounded-full bg-gray-100 px-2 py-0.5 text-xs font-medium text-gray-600 dark:bg-gray-700 dark:text-gray-400"
							>
								{completions.length}
							</span>
						</button>
						<!-- Completions (expanded) -->
						{#if isAreaExpanded('completed', area.id)}
							<div class="space-y-1 border-t border-gray-200 px-3 py-2 dark:border-gray-700">
								{#each completions as completion (completion.id)}
									<div
										class="flex items-center justify-between rounded-lg bg-gray-50 px-3 py-2 dark:bg-gray-700/50"
									>
										<div class="flex items-center gap-3">
											<svg
												class="h-4 w-4 shrink-0 text-green-500"
												fill="none"
												viewBox="0 0 24 24"
												stroke="currentColor"
											>
												<path
													stroke-linecap="round"
													stroke-linejoin="round"
													stroke-width="2"
													d="M5 13l4 4L19 7"
												></path>
											</svg>
											<div>
												<span class="text-sm text-gray-900 dark:text-gray-100">
													{completion.task?.sessionDescription || completion.task?.scopeDescription}
												</span>
												<div class="text-xs text-gray-500 dark:text-gray-400">
													{completion.completedBy?.fullName} - {formatDateTime(
														completion.completedAt
													)}
												</div>
											</div>
										</div>
										{#if isActive && onRemoveCompletedTask}
											<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={() => onRemoveCompletedTask(completion.taskId)}
												aria-label="Remove completion"
											>
												<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="M6 18L18 6M6 6l12 12"
													></path>
												</svg>
											</button>
										{/if}
									</div>
								{/each}
							</div>
						{/if}
					</div>
				{/each}
			</div>
		</div>
	{/if}

	<!-- Available Tasks Section -->
	{#if availableTasksCount > 0 && isActive}
		<div>
			<h4 class="mb-3 font-medium text-gray-900 dark:text-gray-100">
				Available Tasks ({availableTasksCount})
			</h4>
			<div class="space-y-2">
				{#each availableTasksByArea() as { area, tasks: areaTasks }}
					<div
						class="rounded-lg border border-gray-200 bg-white dark:border-gray-700 dark:bg-gray-800 {sessionType ===
						'service'
							? 'border-l-4 border-l-secondary-400'
							: 'border-l-4 border-l-accent-400'}"
					>
						<!-- Area Header -->
						<button
							type="button"
							onclick={() => toggleArea('available', area.id)}
							class="flex w-full items-center gap-2 px-3 py-2 text-left"
						>
							<svg
								class="h-4 w-4 shrink-0 text-gray-500 transition-transform dark:text-gray-400 {isAreaExpanded(
									'available',
									area.id
								)
									? 'rotate-90'
									: ''}"
								fill="none"
								stroke="currentColor"
								viewBox="0 0 24 24"
							>
								<path
									stroke-linecap="round"
									stroke-linejoin="round"
									stroke-width="2"
									d="M9 5l7 7-7 7"
								/>
							</svg>
							<span class="flex-1 text-sm font-medium text-gray-700 dark:text-gray-300"
								>{area.name}</span
							>
							<span
								class="rounded-full bg-blue-100 px-2 py-0.5 text-xs font-medium text-blue-700 dark:bg-blue-900/50 dark:text-blue-400"
							>
								{areaTasks.length}
							</span>
						</button>
						<!-- Tasks (expanded) -->
						{#if isAreaExpanded('available', area.id)}
							<div class="space-y-1 border-t border-gray-200 px-3 py-2 dark:border-gray-700">
								{#each areaTasks as task (task.id)}
									<button
										type="button"
										class="flex w-full items-center justify-between rounded-lg bg-gray-50 px-3 py-2 text-left transition-colors hover:bg-gray-100 dark:bg-gray-800/50 dark:hover:bg-gray-700"
										onclick={() => onToggleTask?.(task.id)}
									>
										<div class="flex items-center gap-3">
											<span
												class="flex h-5 w-5 shrink-0 items-center justify-center rounded border-2 border-gray-300 dark:border-gray-600"
											>
											</span>
											<span class="text-sm text-gray-900 dark:text-gray-100">
												{task.sessionDescription || task.scopeDescription}
											</span>
										</div>
										{#if isServiceTask(task) && task.frequency}
											<span
												class="rounded-full px-2 py-0.5 text-xs font-medium {frequencyColors[
													task.frequency
												] ?? frequencyColors['WEEKLY']}"
											>
												{formatFrequency(task.frequency)}
											</span>
										{/if}
									</button>
								{/each}
							</div>
						{/if}
					</div>
				{/each}
			</div>
		</div>
	{:else if !hasCompletedTasks && !hasReadyToSubmit}
		<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 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"
				></path>
			</svg>
			<p class="mt-2 text-sm text-gray-500 dark:text-gray-400">No tasks available</p>
		</div>
	{/if}
</div>
