<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/projects';

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

	let project = $derived(data.project);

	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'
		});
	}

	// Get active scope
	let activeScope = $derived(
		project.scopes?.find((s) => s.isActive) ?? project.scopes?.[0] ?? null
	);
	let sortedCategories = $derived(
		activeScope?.categories ? [...activeScope.categories].sort((a, b) => a.order - b.order) : []
	);

	// Get address display
	let addressDisplay = $derived(
		project.formattedAddress ||
			(project.streetAddress
				? `${project.streetAddress}, ${project.city}, ${project.state} ${project.zipCode}`
				: project.accountAddress
					? `${project.accountAddress.streetAddress}, ${project.accountAddress.city}, ${project.accountAddress.state} ${project.accountAddress.zipCode}`
					: null)
	);
</script>

<svelte:head>
	<title>{project.name} - Nexus</title>
</svelte:head>

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

		<div class="space-y-6">
			<!-- Location Section -->
			{#if addressDisplay || project.accountAddress}
				<CustomerSectionContainer title="Location" colorScheme="accent">
					<div class="space-y-2">
						{#if project.accountAddress?.name}
							<p class="font-medium text-theme">{project.accountAddress.name}</p>
						{/if}

						{#if addressDisplay}
							<p class="text-theme-secondary">{addressDisplay}</p>
						{/if}
						{#if project.accountAddress?.account}
							<p class="text-sm text-theme-muted">
								Account: {project.accountAddress.account.name}
							</p>
						{/if}
					</div>
				</CustomerSectionContainer>
			{/if}

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

						{#if sortedCategories.length > 0}
							<div class="space-y-4">
								{#each sortedCategories as category (category.id)}
									{@const sortedTasks = [...category.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">{category.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-accent-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 categories defined for this scope.</p>
						{/if}
					</div>
				</CustomerSectionContainer>
			{/if}

			<!-- Team Section -->
			{#if project.teamMembers.length > 0}
				<CustomerSectionContainer title="Assigned Team" colorScheme="accent">
					<div class="grid grid-cols-1 gap-3 sm:grid-cols-2">
						{#each project.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-accent-100 text-accent-600 dark:bg-accent-900/30 dark:text-accent-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 project.notes}
				<CustomerSectionContainer title="Notes" colorScheme="accent">
					<p class="whitespace-pre-wrap text-theme-secondary">{project.notes}</p>
				</CustomerSectionContainer>
			{/if}
		</div>
	</ContentContainer>
</div>
