<script lang="ts">
	import ContentContainer from '$lib/components/layout/ContentContainer.svelte';
	import CustomerPageHeader from '$lib/components/customer/CustomerPageHeader.svelte';
	import { formatDate } from '$lib/utils/date';
	import { getFrequencyLabel } from '$lib/stores/scopeEditor.svelte';
	import { SvelteSet } from 'svelte/reactivity';
	import { goto } from '$app/navigation';
	import type { PageData } from './$types';
	import type { ScopeByAddress$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 ?? {}
	);

	// Get the active scope (first one returned since we filter by isActive)
	let scope = $derived(
		(data as { scope?: { data?: ScopeByAddress$result } }).scope?.data?.scopes?.[0] ?? null
	);

	// Track which scope areas are expanded
	let expandedAreas = new SvelteSet<string>();

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

	function getAccountInfo(accountId: string, addressId: string): { name: string; address: string } {
		// accountId and addressId from services are already UUIDs, not Relay IDs
		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
	);

	function getStatusBadge(status: string): { text: string; classes: string } {
		switch (status) {
			case 'SCHEDULED':
				return {
					text: 'Scheduled',
					classes:
						'bg-secondary-100 text-secondary-700 dark:bg-secondary-900/30 dark:text-secondary-400'
				};
			case 'IN_PROGRESS':
				return {
					text: 'In Progress',
					classes: 'bg-warning-100 text-warning-700 dark:bg-warning-900/30 dark:text-warning-400'
				};
			case 'COMPLETED':
				return {
					text: 'Completed',
					classes: 'bg-success-100 text-success-700 dark:bg-success-900/30 dark:text-success-400'
				};
			default:
				return {
					text: status,
					classes: 'bg-black/10 text-theme-secondary dark:bg-white/10'
				};
		}
	}

	// 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>Service Details - Nexus</title>
</svelte:head>

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

		{#if service}
			{@const statusBadge = getStatusBadge(service.status)}
			<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 px-3 py-1.5 text-sm font-medium {statusBadge.classes}">
							{statusBadge.text}
						</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}

				<!-- Service Checklist (Scope) -->
				{#if scope}
					<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 Checklist</h2>
							{#if scope.description}
								<p class="mt-1 text-sm text-theme-muted">{scope.description}</p>
							{/if}
						</div>
						<div class="p-4">
							{#if scope.areas && scope.areas.length > 0}
								<div class="space-y-2">
									{#each [...scope.areas].sort((a, b) => a.order - b.order) as area (area.id)}
										<div
											class="rounded-lg border border-theme bg-black/[0.02] dark:bg-white/[0.02]"
										>
											<button
												type="button"
												onclick={() => toggleArea(area.id)}
												class="flex w-full items-center justify-between px-3 py-2 text-left"
											>
												<span class="text-sm font-medium text-theme">{area.name}</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>
											</button>

											{#if expandedAreas.has(area.id)}
												<div class="border-t border-theme px-3 py-2">
													{#if area.tasks && area.tasks.length > 0}
														<ul class="space-y-1.5">
															{#each [...area.tasks].sort((a, b) => a.order - b.order) as task (task.id)}
																<li class="flex items-start justify-between gap-2 text-sm">
																	<span class="text-theme-secondary">
																		{task.checklistDescription || task.description}
																	</span>
																	<span
																		class="shrink-0 rounded bg-black/5 px-1.5 py-0.5 text-xs text-theme-muted dark:bg-white/10"
																	>
																		{getFrequencyLabel(task.frequency)}
																	</span>
																</li>
															{/each}
														</ul>
													{:else}
														<p class="text-sm text-theme-muted">No tasks in this area.</p>
													{/if}
												</div>
											{/if}
										</div>
									{/each}
								</div>
							{:else}
								<p class="text-sm text-theme-muted">No checklist items defined.</p>
							{/if}
						</div>
					</div>
				{/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>
