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

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

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

	// Expanded state for sections
	let expandedAreas = new SvelteSet<string>();
	let expandedCompletedAreas = new SvelteSet<string>();
	let expandedReadyAreas = new SvelteSet<string>();
	let completedExpanded = $state(true);
	let availableExpanded = $state(true);

	function toggleAreaExpanded(areaId: string) {
		if (expandedAreas.has(areaId)) {
			expandedAreas.delete(areaId);
		} else {
			expandedAreas.add(areaId);
		}
	}

	function toggleCompletedAreaExpanded(areaId: string) {
		if (expandedCompletedAreas.has(areaId)) {
			expandedCompletedAreas.delete(areaId);
		} else {
			expandedCompletedAreas.add(areaId);
		}
	}

	function toggleReadyAreaExpanded(areaId: string) {
		if (expandedReadyAreas.has(areaId)) {
			expandedReadyAreas.delete(areaId);
		} else {
			expandedReadyAreas.add(areaId);
		}
	}

	// Get available tasks (not selected, not completed)
	let availableTasks = $derived(
		tasks.filter((t) => !completedTaskIds.has(t.uuid) && !selectedTaskIds.has(t.uuid))
	);

	// Group available tasks by area
	let availableTasksByArea = $derived(() => {
		const grouped = new SvelteMap<string, ExtendedTask[]>();
		for (const task of availableTasks) {
			const existing = grouped.get(task.areaId) || [];
			existing.push(task);
			grouped.set(task.areaId, existing);
		}
		return Array.from(grouped.entries()).map(([areaId, areaTasks]) => {
			const area = areas.find((a) => a.id === areaId);
			return { area, tasks: areaTasks };
		});
	});

	// Color classes based on session type
	let colorClasses = $derived(
		sessionType === 'service'
			? {
					primary: 'text-secondary-600 dark:text-secondary-400',
					bg: 'bg-secondary-500/10',
					border: 'border-secondary-500/30',
					button: 'bg-secondary-500 hover:bg-secondary-600 text-white'
				}
			: {
					primary: 'text-accent-600 dark:text-accent-400',
					bg: 'bg-accent-500/10',
					border: 'border-accent-500/30',
					button: 'bg-accent-500 hover:bg-accent-600 text-white'
				}
	);
</script>

{#if !hasScope}
	<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="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"
			/>
		</svg>
		<h2 class="empty-state-title">No Scope Assigned</h2>
		<p class="empty-state-text">This {sessionType} doesn't have a scope of work assigned.</p>
	</div>
{:else}
	<div class="space-y-6">
		<!-- Ready to Submit Section -->
		{#if selectedTaskIds.size > 0}
			<div class="rounded-xl border-2 {colorClasses.border} {colorClasses.bg} p-4">
				<div class="mb-4 flex items-center justify-between">
					<h3 class="font-semibold {colorClasses.primary}">
						Ready to Submit ({selectedTaskIds.size})
					</h3>
					<div class="flex items-center gap-2">
						<button
							type="button"
							onclick={onClearSelection}
							class="text-sm text-theme-muted hover:text-theme"
						>
							Clear all
						</button>
						<button
							type="button"
							onclick={onSubmitAllTasks}
							disabled={isSubmitting}
							class="rounded-lg px-4 py-2 text-sm font-medium {colorClasses.button} disabled:opacity-50"
						>
							{isSubmitting ? 'Submitting...' : 'Submit All'}
						</button>
					</div>
				</div>

				<div class="space-y-3">
					{#each readyToSubmitByArea as { area, tasks: areaTasks } (area?.id ?? 'unknown')}
						{#if area}
							<div>
								<button
									type="button"
									onclick={() => toggleReadyAreaExpanded(area.id)}
									class="flex w-full items-center justify-between py-1 text-left"
								>
									<span class="text-sm font-medium {colorClasses.primary}">{area.name}</span>
									<span class="flex items-center gap-2">
										<span class="text-xs text-theme-muted">{areaTasks.length} tasks</span>
										<svg
											class="h-4 w-4 text-theme-muted transition-transform {expandedReadyAreas.has(
												area.id
											)
												? 'rotate-180'
												: ''}"
											style="fill: none"
											stroke="currentColor"
											viewBox="0 0 24 24"
										>
											<path
												stroke-linecap="round"
												stroke-linejoin="round"
												stroke-width="2"
												d="M19 9l-7 7-7-7"
											/>
										</svg>
									</span>
								</button>

								{#if expandedReadyAreas.has(area.id)}
									<div class="mt-2 space-y-2 border-l-2 pl-2 {colorClasses.border}">
										{#each areaTasks as task (task.uuid)}
											<div class="flex items-start gap-3 rounded-lg bg-white p-2 dark:bg-gray-800">
												<div class="min-w-0 flex-1">
													<p class="text-sm text-theme">
														{task.checklistDescription || task.description}
													</p>
													<div class="mt-1 flex items-center gap-2">
														{#if sessionType === 'service' && 'frequency' in task && task.frequency}
															<span
																class="rounded px-1.5 py-0.5 text-xs font-medium {frequencyColors[
																	task.frequency
																] || 'bg-gray-100 text-gray-600'}"
															>
																{formatFrequency(task.frequency)}
															</span>
														{/if}
														{#if task.estimatedMinutes}
															<span class="text-xs text-theme-muted"
																>{task.estimatedMinutes} min</span
															>
														{/if}
													</div>
												</div>
												<div class="flex items-center gap-1">
													<button
														type="button"
														onclick={() => onSubmitTask(task.uuid)}
														disabled={submittingTaskId === task.uuid}
														class="rounded p-1.5 {colorClasses.button} disabled:opacity-50"
														title="Submit task"
													>
														{#if submittingTaskId === task.uuid}
															<svg
																class="h-4 w-4 animate-spin"
																viewBox="0 0 24 24"
																style="fill: none"
															>
																<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 12h4z"
																></path>
															</svg>
														{: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="M5 13l4 4L19 7"
																/>
															</svg>
														{/if}
													</button>
													<button
														type="button"
														onclick={() => onRemoveTask(task.uuid)}
														class="rounded p-1.5 text-theme-muted hover:bg-error-50 hover:text-error-500 dark:hover:bg-error-900/20"
														title="Remove from selection"
													>
														<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="M6 18L18 6M6 6l12 12"
															/>
														</svg>
													</button>
												</div>
											</div>
										{/each}
									</div>
								{/if}
							</div>
						{/if}
					{/each}
				</div>
			</div>
		{/if}

		<!-- Completed Tasks Section -->
		{#if completedTasksByArea.length > 0}
			<div class="card-padded">
				<button
					type="button"
					onclick={() => (completedExpanded = !completedExpanded)}
					class="flex w-full items-center justify-between"
				>
					<span class="font-semibold text-theme">
						Completed Tasks ({completedTasksByArea.reduce(
							(sum, a) => sum + a.completions.length,
							0
						)})
					</span>
					<svg
						class="h-5 w-5 text-theme-muted transition-transform {completedExpanded
							? 'rotate-180'
							: ''}"
						style="fill: none"
						stroke="currentColor"
						viewBox="0 0 24 24"
					>
						<path
							stroke-linecap="round"
							stroke-linejoin="round"
							stroke-width="2"
							d="M19 9l-7 7-7-7"
						/>
					</svg>
				</button>

				{#if completedExpanded}
					<div class="mt-4 space-y-3">
						{#each completedTasksByArea as { area, completions } (area.id)}
							<div>
								<button
									type="button"
									onclick={() => toggleCompletedAreaExpanded(area.id)}
									class="flex w-full items-center justify-between py-1 text-left"
								>
									<span class="text-sm font-medium text-success">{area.name}</span>
									<span class="flex items-center gap-2">
										<span class="text-xs text-theme-muted">{completions.length} tasks</span>
										<svg
											class="h-4 w-4 text-theme-muted transition-transform {expandedCompletedAreas.has(
												area.id
											)
												? 'rotate-180'
												: ''}"
											style="fill: none"
											stroke="currentColor"
											viewBox="0 0 24 24"
										>
											<path
												stroke-linecap="round"
												stroke-linejoin="round"
												stroke-width="2"
												d="M19 9l-7 7-7-7"
											/>
										</svg>
									</span>
								</button>

								{#if expandedCompletedAreas.has(area.id)}
									<div class="mt-2 space-y-2 border-l-2 border-success-500/30 pl-2">
										{#each completions as completion (completion.id)}
											{@const task = tasks.find((t) => t.uuid === completion.taskId)}
											<div
												class="flex items-start gap-3 rounded-lg border border-success bg-success p-3"
											>
												<svg
													class="mt-0.5 h-5 w-5 flex-shrink-0 text-success-500"
													style="fill: none"
													stroke="currentColor"
													viewBox="0 0 24 24"
												>
													<path
														stroke-linecap="round"
														stroke-linejoin="round"
														stroke-width="2"
														d="M5 13l4 4L19 7"
													/>
												</svg>
												<div class="min-w-0 flex-1">
													<p class="text-sm text-theme">
														{#if task}
															{task.checklistDescription || task.description}
														{:else}
															Task
														{/if}
													</p>
													{#if task && sessionType === 'service' && 'frequency' in task && task.frequency}
														<div class="mt-1">
															<span
																class="rounded px-1.5 py-0.5 text-xs font-medium {frequencyColors[
																	task.frequency
																] || 'bg-gray-100 text-gray-600'}"
															>
																{formatFrequency(task.frequency)}
															</span>
														</div>
													{/if}
													<p class="mt-1 text-xs text-theme-muted">
														{getTeamMemberName(completion.completedById)} &middot; {formatDateTime(
															completion.completedAt
														)}
													</p>
												</div>
												{#if isActive}
													<button
														type="button"
														onclick={() => onRemoveCompletedTask(completion.taskId)}
														disabled={removingTaskId === completion.taskId}
														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="Remove completion"
													>
														{#if removingTaskId === completion.taskId}
															<svg
																class="h-4 w-4 animate-spin"
																viewBox="0 0 24 24"
																style="fill: none"
															>
																<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 12h4z"
																></path>
															</svg>
														{: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>
												{/if}
											</div>
										{/each}
									</div>
								{/if}
							</div>
						{/each}
					</div>
				{/if}
			</div>
		{/if}

		<!-- Available Tasks Section -->
		{#if isActive && availableTasksCount > 0}
			<div class="card-padded">
				<button
					type="button"
					onclick={() => (availableExpanded = !availableExpanded)}
					class="flex w-full items-center justify-between"
				>
					<span class="font-semibold text-theme">
						Available Tasks ({availableTasksCount})
					</span>
					<svg
						class="h-5 w-5 text-theme-muted transition-transform {availableExpanded
							? 'rotate-180'
							: ''}"
						style="fill: none"
						stroke="currentColor"
						viewBox="0 0 24 24"
					>
						<path
							stroke-linecap="round"
							stroke-linejoin="round"
							stroke-width="2"
							d="M19 9l-7 7-7-7"
						/>
					</svg>
				</button>

				{#if availableExpanded}
					<div class="mt-4 space-y-4">
						{#each availableTasksByArea() as { area, tasks: areaTasks } (area?.id ?? 'unknown')}
							{#if area}
								<div>
									<button
										type="button"
										onclick={() => toggleAreaExpanded(area.id)}
										class="flex w-full items-center justify-between text-left"
									>
										<span class="text-sm font-medium {colorClasses.primary}">{area.name}</span>
										<span class="flex items-center gap-2">
											<span class="text-xs text-theme-muted">{areaTasks.length} tasks</span>
											<svg
												class="h-4 w-4 text-theme-muted transition-transform {expandedAreas.has(
													area.id
												)
													? 'rotate-180'
													: ''}"
												style="fill: none"
												stroke="currentColor"
												viewBox="0 0 24 24"
											>
												<path
													stroke-linecap="round"
													stroke-linejoin="round"
													stroke-width="2"
													d="M19 9l-7 7-7-7"
												/>
											</svg>
										</span>
									</button>

									{#if expandedAreas.has(area.id)}
										<div class="mt-2 space-y-2 border-l-2 pl-2 {colorClasses.border}">
											{#each areaTasks as task (task.uuid)}
												<div
													class="flex w-full items-start gap-3 rounded-lg bg-gray-50 p-3 dark:bg-gray-800/50"
												>
													<div class="min-w-0 flex-1">
														<p class="text-sm text-theme">
															{task.checklistDescription || task.description}
														</p>
														<div class="mt-1 flex items-center gap-2">
															{#if sessionType === 'service' && 'frequency' in task && task.frequency}
																<span
																	class="rounded px-1.5 py-0.5 text-xs font-medium {frequencyColors[
																		task.frequency
																	] || 'bg-gray-100 text-gray-600'}"
																>
																	{formatFrequency(task.frequency)}
																</span>
															{/if}
															{#if task.estimatedMinutes}
																<span class="text-xs text-theme-muted"
																	>{task.estimatedMinutes} min</span
																>
															{/if}
														</div>
													</div>
													<button
														type="button"
														onclick={() => onToggleTask(task.uuid)}
														class="rounded-lg px-3 py-1.5 text-xs font-medium {colorClasses.button}"
													>
														Add
													</button>
												</div>
											{/each}
										</div>
									{/if}
								</div>
							{/if}
						{/each}
					</div>
				{/if}
			</div>
		{:else if !isActive}
			<div class="card-padded">
				<p class="py-4 text-center text-sm text-theme-muted">
					This session is closed. Tasks cannot be added or modified.
				</p>
			</div>
		{/if}
	</div>
{/if}
