<script lang="ts">
	import ContentContainer from '$lib/components/layout/ContentContainer.svelte';
	import CustomerPageHeader from '$lib/components/customer/CustomerPageHeader.svelte';
	import { formatDate, formatDateTime } from '$lib/utils/date';
	import { SvelteMap, SvelteSet } from 'svelte/reactivity';
	import { goto } from '$app/navigation';
	import type { PageData } from './$types';
	import type {
		ServiceSessionByService$result,
		ScopeByAddress$result,
		TeamProfiles$result
	} from '$houdini';

	let { data }: { data: PageData } = $props();

	let service = $derived(data.service?.data?.service);
	let customerAccountLookup = $derived(
		(
			data as {
				customerAccountLookup?: Record<
					string,
					{
						name: string;
						addressName?: string;
						streetAddress?: string;
						city?: string;
						state?: string;
					}
				>;
			}
		).customerAccountLookup ?? {}
	);

	// Session data
	type SessionData = ServiceSessionByService$result['serviceSessions'][number];
	let session = $derived(
		(data as { session?: { data?: ServiceSessionByService$result } }).session?.data
			?.serviceSessions?.[0] ?? null
	);

	// Scope data for task lookups
	let scope = $derived(
		(data as { scope?: { data?: ScopeByAddress$result } }).scope?.data?.scopes?.[0] ?? null
	);

	// Team profiles for attribution
	let teamProfiles = $derived(
		(data as { teamProfiles?: { data?: TeamProfiles$result } }).teamProfiles?.data?.teamProfiles ??
			[]
	);

	// Build task lookup map from scope (key by both global ID and UUID)
	let taskLookup = $derived.by(() => {
		const map = new SvelteMap<string, { description: string; areaName: string }>();
		if (scope?.areas) {
			for (const area of scope.areas) {
				for (const task of area.tasks ?? []) {
					const taskInfo = {
						description: task.checklistDescription || task.description,
						areaName: area.name
					};
					// Store by global ID
					map.set(task.id, taskInfo);
					// Also extract and store by UUID for matching with completedTask.taskId
					try {
						const decoded = atob(task.id);
						const sep = decoded.indexOf(':');
						if (sep > 0) {
							const uuid = decoded.slice(sep + 1);
							map.set(uuid, taskInfo);
						}
					} catch {
						/* ignore decode errors */
					}
				}
			}
		}
		return map;
	});

	// Build team profile lookup map
	let teamProfileLookup = $derived.by(() => {
		const map = new SvelteMap<string, string>();
		for (const profile of teamProfiles) {
			// Store by both global ID and UUID for flexible lookup
			map.set(profile.id, profile.fullName);
			// Also extract UUID from global ID if present
			try {
				const decoded = atob(profile.id);
				const sep = decoded.indexOf(':');
				if (sep > 0) {
					const uuid = decoded.slice(sep + 1);
					map.set(uuid, profile.fullName);
				}
			} catch {
				/* ignore decode errors */
			}
		}
		return map;
	});

	// Session media (separate from session for proper typing)
	let sessionPhotos = $derived(data.sessionPhotos?.serviceSessionImages ?? []);
	let sessionVideos = $derived(data.sessionVideos?.serviceSessionVideos ?? []);

	// Filter to only public items (internal: false)
	let publicPhotos = $derived(sessionPhotos.filter((p) => !p.internal));
	let publicNotes = $derived(session?.notes?.filter((n) => !n.internal) ?? []);
	let publicVideos = $derived(sessionVideos.filter((v) => !v.internal));

	// Group completed tasks by area
	let tasksByArea = $derived.by(() => {
		const grouped = new SvelteMap<
			string,
			Array<{
				task: NonNullable<SessionData['completedTasks']>[number];
				taskInfo: { description: string; areaName: string } | undefined;
			}>
		>();

		for (const completedTask of session?.completedTasks ?? []) {
			const taskInfo = taskLookup.get(completedTask.taskId);
			const areaName = taskInfo?.areaName ?? 'Other';

			if (!grouped.has(areaName)) {
				grouped.set(areaName, []);
			}
			grouped.get(areaName)!.push({ task: completedTask, taskInfo });
		}

		return grouped;
	});

	// Track expanded areas
	let expandedAreas = new SvelteSet<string>();
	// Expand all by default
	$effect(() => {
		for (const areaName of tasksByArea.keys()) {
			expandedAreas.add(areaName);
		}
	});

	function toggleArea(areaName: string) {
		if (expandedAreas.has(areaName)) {
			expandedAreas.delete(areaName);
		} else {
			expandedAreas.add(areaName);
		}
	}

	function getTeamMemberName(profileId: string): string {
		return teamProfileLookup.get(profileId) ?? 'Team Member';
	}

	function formatDuration(seconds: number): string {
		const hours = Math.floor(seconds / 3600);
		const minutes = Math.floor((seconds % 3600) / 60);
		if (hours > 0) {
			return `${hours}h ${minutes}m`;
		}
		return `${minutes}m`;
	}

	function getAccountInfo(accountId: string, addressId: string): { name: string; address: string } {
		const addrInfo = customerAccountLookup[addressId];
		if (addrInfo) {
			return {
				name: addrInfo.addressName ? `${addrInfo.name} - ${addrInfo.addressName}` : addrInfo.name,
				address: `${addrInfo.streetAddress || ''}, ${addrInfo.city || ''}, ${addrInfo.state || ''}`
			};
		}
		const acctInfo = customerAccountLookup[accountId];
		if (acctInfo) {
			return {
				name: acctInfo.name,
				address: `${acctInfo.streetAddress || ''}, ${acctInfo.city || ''}, ${acctInfo.state || ''}`
			};
		}
		return { name: 'Unknown Account', address: '' };
	}

	let accountInfo = $derived(
		service ? getAccountInfo(service.accountId, service.accountAddressId) : null
	);

	// Photo lightbox state
	let selectedPhoto = $state<(typeof sessionPhotos)[number] | null>(null);

	// Navigate to new message page with service entity pre-filled
	function messageAboutService() {
		if (!service) return;
		const dateStr = formatDate(service.date) || 'Service';
		const accountName = accountInfo?.name ?? 'Unknown';
		const subject = `${dateStr} - Service: ${accountName}`;

		const params = new URLSearchParams({
			entityType: 'Service',
			entityId: service.id,
			subject
		});
		goto(`/messages/new?${params.toString()}`);
	}
</script>

<svelte:head>
	<title>Completed Service - Nexus</title>
</svelte:head>

<div class="py-8">
	<ContentContainer>
		<CustomerPageHeader
			title="Completed Service"
			subtitle={service ? formatDate(service.date) : undefined}
			colorScheme="secondary"
			backHref="/customer/history"
		/>

		{#if service}
			<div class="space-y-6">
				<!-- Status & Date Card -->
				<div class="rounded-xl border border-theme bg-theme-card p-4">
					<div class="flex items-center justify-between">
						<div>
							<p class="text-sm text-theme-muted">Service Date</p>
							<p class="text-xl font-semibold text-theme">{formatDate(service.date)}</p>
						</div>
						<span
							class="rounded-lg bg-success-100 px-3 py-1.5 text-sm font-medium text-success-700 dark:bg-success-900/30 dark:text-success-400"
						>
							Completed
						</span>
					</div>
				</div>

				<!-- Message Support Button -->
				<button
					type="button"
					onclick={messageAboutService}
					class="flex w-full items-center justify-center gap-2 rounded-xl border border-theme bg-theme-card px-4 py-3 text-sm font-medium text-primary-600 transition-colors hover:bg-primary-50 dark:text-primary-400 dark:hover:bg-primary-900/20"
				>
					<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="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"
						/>
					</svg>
					Message Support About This Service
				</button>

				<!-- Location Card -->
				{#if accountInfo}
					<div class="rounded-xl border border-theme bg-theme-card">
						<div class="border-b border-theme px-4 py-3">
							<h2 class="font-semibold text-theme">Location</h2>
						</div>
						<div class="p-4">
							<p class="font-medium text-theme">{accountInfo.name}</p>
							<p class="text-sm text-theme-secondary">{accountInfo.address}</p>
						</div>
					</div>
				{/if}

				<!-- Notes Card (if any) -->
				{#if service.notes}
					<div class="rounded-xl border border-theme bg-theme-card">
						<div class="border-b border-theme px-4 py-3">
							<h2 class="font-semibold text-theme">Notes</h2>
						</div>
						<div class="p-4">
							<p class="text-sm whitespace-pre-wrap text-theme-secondary">{service.notes}</p>
						</div>
					</div>
				{/if}

				<!-- Session Information -->
				{#if session}
					<!-- Session Summary -->
					<div class="rounded-xl border border-theme bg-theme-card">
						<div class="border-b border-theme px-4 py-3">
							<h2 class="font-semibold text-theme">Service Summary</h2>
						</div>
						<div class="p-4">
							<div class="grid grid-cols-2 gap-4 sm:grid-cols-3">
								{#if session.durationSeconds}
									<div>
										<p class="text-xs text-theme-muted uppercase">Duration</p>
										<p class="text-lg font-semibold text-theme">
											{formatDuration(session.durationSeconds)}
										</p>
									</div>
								{/if}
								<div>
									<p class="text-xs text-theme-muted uppercase">Tasks Completed</p>
									<p class="text-lg font-semibold text-theme">
										{session.completedTasks?.length ?? 0}
									</p>
								</div>
								{#if publicPhotos.length > 0}
									<div>
										<p class="text-xs text-theme-muted uppercase">Photos</p>
										<p class="text-lg font-semibold text-theme">{publicPhotos.length}</p>
									</div>
								{/if}
							</div>
						</div>
					</div>

					<!-- Completed Tasks -->
					{#if session.completedTasks && session.completedTasks.length > 0}
						<div class="rounded-xl border border-theme bg-theme-card">
							<div class="border-b border-theme px-4 py-3">
								<h2 class="font-semibold text-theme">Completed Tasks</h2>
							</div>
							<div class="p-4">
								<div class="space-y-2">
									{#each [...tasksByArea.entries()] as [areaName, tasks] (areaName)}
										<div
											class="rounded-lg border border-theme bg-black/[0.02] dark:bg-white/[0.02]"
										>
											<button
												type="button"
												onclick={() => toggleArea(areaName)}
												class="flex w-full items-center justify-between px-3 py-2 text-left"
											>
												<span class="text-sm font-medium text-theme">{areaName}</span>
												<span class="flex items-center gap-2">
													<span
														class="rounded bg-success-100 px-1.5 py-0.5 text-xs text-success-700 dark:bg-success-900/30 dark:text-success-400"
													>
														{tasks.length} completed
													</span>
													<svg
														class="h-4 w-4 text-theme-muted transition-transform {expandedAreas.has(
															areaName
														)
															? '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(areaName)}
												<div class="border-t border-theme px-3 py-2">
													<ul class="space-y-2">
														{#each tasks as { task, taskInfo } (task.id)}
															<li class="flex items-start gap-2 text-sm">
																<svg
																	class="mt-0.5 h-4 w-4 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">
																	<span class="text-theme-secondary"
																		>{taskInfo?.description ?? 'Task'}</span
																	>
																	<p class="text-xs text-theme-muted">
																		{getTeamMemberName(task.completedById)} &middot; {formatDateTime(
																			task.completedAt
																		)}
																	</p>
																	{#if task.notes}
																		<p class="mt-1 text-xs text-theme-muted italic">
																			"{task.notes}"
																		</p>
																	{/if}
																</div>
															</li>
														{/each}
													</ul>
												</div>
											{/if}
										</div>
									{/each}
								</div>
							</div>
						</div>
					{/if}

					<!-- Photos -->
					{#if publicPhotos.length > 0}
						<div class="rounded-xl border border-theme bg-theme-card">
							<div class="border-b border-theme px-4 py-3">
								<h2 class="font-semibold text-theme">Photos</h2>
							</div>
							<div class="p-4">
								<div class="grid grid-cols-2 gap-3 sm:grid-cols-3 md:grid-cols-4">
									{#each publicPhotos as photo (photo.id)}
										<button
											type="button"
											onclick={() => (selectedPhoto = photo)}
											class="group relative aspect-square overflow-hidden rounded-lg border border-theme bg-black/5 dark:bg-white/5"
										>
											{#if photo.thumbnail?.url}
												<img
													src={photo.thumbnail.url}
													alt={photo.title || 'Service photo'}
													class="h-full w-full object-cover transition-transform group-hover:scale-105"
												/>
											{:else if photo.image?.url}
												<img
													src={photo.image.url}
													alt={photo.title || 'Service photo'}
													class="h-full w-full object-cover transition-transform group-hover:scale-105"
												/>
											{/if}
											<span
												class="absolute inset-0 bg-black/0 transition-colors group-hover:bg-black/10"
											></span>
										</button>
									{/each}
								</div>
							</div>
						</div>
					{/if}

					<!-- Service Notes from Session -->
					{#if publicNotes.length > 0}
						<div class="rounded-xl border border-theme bg-theme-card">
							<div class="border-b border-theme px-4 py-3">
								<h2 class="font-semibold text-theme">Service Notes</h2>
							</div>
							<div class="divide-theme divide-y">
								{#each publicNotes as note (note.id)}
									<div class="p-4">
										<p class="text-sm whitespace-pre-wrap text-theme-secondary">{note.content}</p>
										<p class="mt-2 text-xs text-theme-muted">
											{getTeamMemberName(note.authorId)} &middot; {formatDateTime(note.createdAt)}
										</p>
									</div>
								{/each}
							</div>
						</div>
					{/if}

					<!-- Videos -->
					{#if publicVideos.length > 0}
						<div class="rounded-xl border border-theme bg-theme-card">
							<div class="border-b border-theme px-4 py-3">
								<h2 class="font-semibold text-theme">Videos</h2>
							</div>
							<div class="p-4">
								<div class="grid grid-cols-1 gap-4 sm:grid-cols-2">
									{#each publicVideos as video (video.id)}
										<div class="overflow-hidden rounded-lg border border-theme">
											{#if video.video?.url}
												<video controls class="w-full" poster={video.thumbnail?.url}>
													<source src={video.video.url} type={video.contentType || 'video/mp4'} />
													<track kind="captions" src="" default />
													Your browser does not support the video tag.
												</video>
											{/if}
											{#if video.title || video.notes}
												<div class="border-t border-theme bg-black/[0.02] p-3 dark:bg-white/[0.02]">
													{#if video.title}
														<p class="text-sm font-medium text-theme">{video.title}</p>
													{/if}
													{#if video.notes}
														<p class="text-xs text-theme-muted">{video.notes}</p>
													{/if}
												</div>
											{/if}
										</div>
									{/each}
								</div>
							</div>
						</div>
					{/if}
				{/if}
			</div>
		{:else}
			<div class="rounded-xl border border-theme bg-theme-card p-8 text-center">
				<p class="text-theme-muted">Service not found.</p>
			</div>
		{/if}
	</ContentContainer>
</div>

<!-- Photo Lightbox -->
{#if selectedPhoto}
	<button
		type="button"
		onclick={() => (selectedPhoto = null)}
		class="fixed inset-0 z-50 flex items-center justify-center bg-black/80 p-4"
	>
		<span class="sr-only">Close photo</span>
		<img
			src={selectedPhoto.image?.url ?? selectedPhoto.thumbnail?.url}
			alt={selectedPhoto.title || 'Service photo'}
			class="max-h-full max-w-full object-contain"
		/>
		{#if selectedPhoto.title || selectedPhoto.notes}
			<span class="absolute right-4 bottom-4 left-4 rounded-lg bg-black/60 p-3 text-white">
				{#if selectedPhoto.title}
					<span class="block font-medium">{selectedPhoto.title}</span>
				{/if}
				{#if selectedPhoto.notes}
					<span class="block text-sm opacity-80">{selectedPhoto.notes}</span>
				{/if}
			</span>
		{/if}
		<span class="absolute top-4 right-4 rounded-full bg-white/20 p-2 text-white hover:bg-white/30">
			<svg class="h-6 w-6" 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>
		</span>
	</button>
{/if}
