<script lang="ts">
	import type { PageData } from './$types';
	import { ContentContainer } from '$lib/components/layout';
	import { CustomerPageHeader, CustomerSectionContainer } from '$lib/components/customer';
	import type { WorkStatus } from '$lib/graphql/queries/services';

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

	let service = $derived(data.service);

	function getStatusBadgeClass(status: WorkStatus): string {
		switch (status) {
			case 'SCHEDULED':
				return 'badge-primary';
			case 'IN_PROGRESS':
				return 'badge-warning';
			case 'COMPLETED':
				return 'badge-success';
			case 'CANCELLED':
				return 'badge-error';
			default:
				return 'badge-neutral';
		}
	}

	function formatStatusLabel(status: WorkStatus): string {
		switch (status) {
			case 'IN_PROGRESS':
				return 'In Progress';
			default:
				return status.charAt(0) + status.slice(1).toLowerCase();
		}
	}

	function formatDate(dateStr: string): string {
		const date = new Date(dateStr + 'T00:00:00');
		return date.toLocaleDateString('en-US', {
			weekday: 'long',
			year: 'numeric',
			month: 'long',
			day: 'numeric'
		});
	}

	function formatAddress(address: {
		streetAddress: string;
		city: string;
		state: string;
		zipCode: string;
	}): string {
		return `${address.streetAddress}, ${address.city}, ${address.state} ${address.zipCode}`;
	}

	// Get location display name
	let locationName = $derived(
		service.accountAddress?.name || service.accountAddress?.city || 'Service Location'
	);

	// Get scope areas sorted by order
	let scope = $derived(service.accountAddress?.activeScope ?? null);
	let sortedAreas = $derived(
		scope?.areas ? [...scope.areas].sort((a, b) => a.order - b.order) : []
	);
</script>

<svelte:head>
	<title>{service.account?.name ?? 'Service'} - Nexus</title>
</svelte:head>

<div class="py-8">
	<ContentContainer maxWidth="4xl">
		<CustomerPageHeader
			title={service.account?.name ?? 'Service'}
			subtitle={formatDate(service.date)}
			backHref="/customer/schedule"
			colorScheme="secondary"
		>
			<span class={getStatusBadgeClass(service.status)}>
				{formatStatusLabel(service.status)}
			</span>
		</CustomerPageHeader>

		<div class="space-y-6">
			<!-- Location Section -->
			{#if service.accountAddress}
				<CustomerSectionContainer title="Location" colorScheme="secondary">
					<div class="space-y-2">
						{#if service.accountAddress.name}
							<p class="font-medium text-theme">{service.accountAddress.name}</p>
						{/if}
						<p class="text-theme-secondary">{service.accountAddress.streetAddress}</p>
						<p class="text-theme-muted">
							{service.accountAddress.city}, {service.accountAddress.state}
							{service.accountAddress.zipCode}
						</p>
					</div>
				</CustomerSectionContainer>
			{/if}

			<!-- Scope & Tasks Section -->
			{#if scope}
				<CustomerSectionContainer title="Scope of Work" colorScheme="secondary">
					<div class="space-y-4">
						<div>
							<h4 class="font-medium text-theme">{scope.name}</h4>
							{#if scope.description}
								<p class="mt-1 text-sm text-theme-secondary">{scope.description}</p>
							{/if}
						</div>

						{#if sortedAreas.length > 0}
							<div class="space-y-4">
								{#each sortedAreas as area (area.id)}
									{@const sortedTasks = [...area.tasks].sort((a, b) => a.order - b.order)}
									<div class="bg-theme-secondary/50 rounded-lg border border-theme p-3">
										<h5 class="mb-2 font-medium text-theme">{area.name}</h5>
										{#if sortedTasks.length > 0}
											<ul class="space-y-1">
												{#each sortedTasks as task (task.id)}
													<li class="flex items-start gap-2 text-sm">
														<span class="mt-1.5 h-1.5 w-1.5 shrink-0 rounded-full bg-secondary-500"
														></span>
														<span class="text-theme-secondary">{task.scopeDescription}</span>
													</li>
												{/each}
											</ul>
										{:else}
											<p class="text-sm text-theme-muted italic">No tasks defined</p>
										{/if}
									</div>
								{/each}
							</div>
						{:else}
							<p class="text-theme-muted">No work areas defined for this scope.</p>
						{/if}
					</div>
				</CustomerSectionContainer>
			{/if}

			<!-- Team Section -->
			{#if service.teamMembers.length > 0}
				<CustomerSectionContainer title="Assigned Team" colorScheme="secondary">
					<div class="grid grid-cols-1 gap-3 sm:grid-cols-2">
						{#each service.teamMembers as member (member.id)}
							<div
								class="bg-theme-secondary/50 flex items-center gap-3 rounded-lg border border-theme p-3"
							>
								<div
									class="flex h-8 w-8 items-center justify-center rounded-full bg-secondary-100 text-secondary-600 dark:bg-secondary-900/30 dark:text-secondary-400"
								>
									<svg class="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
										<path
											stroke-linecap="round"
											stroke-linejoin="round"
											stroke-width="2"
											d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"
										/>
									</svg>
								</div>
								<div>
									<p class="text-sm font-medium text-theme">
										{member.teamProfile?.fullName ?? 'Team Member'}
									</p>
									{#if member.teamProfile?.role}
										<p class="text-xs text-theme-muted">
											{member.teamProfile.role === 'TEAM_LEADER' ? 'Team Leader' : 'Team Member'}
										</p>
									{/if}
								</div>
							</div>
						{/each}
					</div>
				</CustomerSectionContainer>
			{/if}

			<!-- Notes Section -->
			{#if service.notes}
				<CustomerSectionContainer title="Notes" colorScheme="secondary">
					<p class="whitespace-pre-wrap text-theme-secondary">{service.notes}</p>
				</CustomerSectionContainer>
			{/if}
		</div>
	</ContentContainer>
</div>
