<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 { SvelteSet } from 'svelte/reactivity';
	import { goto } from '$app/navigation';
	import type { PageData } from './$types';
	import type { ProjectScope$result } from '$houdini';
	import type { CustomerAccountInfo } from '../../../+layout.server';

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

	let project = $derived(data.project?.data?.project);

	// Customer account lookup for account-affiliated projects (plain object from server)
	let customerAccountLookup = $derived(
		(data as { customerAccountLookup?: Record<string, CustomerAccountInfo> })
			.customerAccountLookup ?? {}
	);

	// Get account info if project is affiliated with an account address
	let accountInfo = $derived.by(() => {
		if (!project?.accountAddressId) return null;
		const addrInfo = customerAccountLookup[project.accountAddressId];
		if (addrInfo) {
			return {
				name: addrInfo.addressName ? `${addrInfo.name} - ${addrInfo.addressName}` : addrInfo.name,
				streetAddress: addrInfo.streetAddress,
				city: addrInfo.city,
				state: addrInfo.state
			};
		}
		return null;
	});

	// Get the project scope
	let scope = $derived(
		(data as { scope?: { data?: ProjectScope$result } }).scope?.data?.projectScope ?? 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 getStatusBadge(status: string): { text: string; classes: string } {
		switch (status) {
			case 'SCHEDULED':
				return {
					text: 'Scheduled',
					classes: 'bg-accent-100 text-accent-700 dark:bg-accent-900/30 dark:text-accent-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 project entity pre-filled
	function messageAboutProject() {
		if (!project) return;
		const dateStr = formatDate(project.date) || '';
		const projectName = project.name || 'Project';
		const ownerName = accountInfo?.name ?? '';
		const parts = [dateStr, `Project: ${projectName}`, ownerName].filter(Boolean);
		const subject = parts.join(' - ');

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

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

<div class="py-8">
	<ContentContainer>
		<CustomerPageHeader
			title={project?.name ?? 'Project'}
			subtitle={project ? formatDate(project.date) : undefined}
			colorScheme="accent"
			backHref="/customer/schedule"
		/>

		{#if project}
			{@const statusBadge = getStatusBadge(project.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">Project Date</p>
							<p class="text-xl font-semibold text-theme">{formatDate(project.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={messageAboutProject}
					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 Project
				</button>

				<!-- Location Card -->
				<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">
						{#if accountInfo}
							<p class="mb-1 text-xs font-medium text-theme-muted uppercase">Account</p>
							<p class="font-medium text-theme">{accountInfo.name}</p>
							<p class="mt-2 font-medium text-theme">{accountInfo.streetAddress}</p>
							<p class="text-sm text-theme-secondary">
								{accountInfo.city}, {accountInfo.state}
							</p>
						{:else}
							<p class="font-medium text-theme">{project.streetAddress}</p>
							<p class="text-sm text-theme-secondary">
								{project.city}, {project.state}
								{project.zipCode}
							</p>
						{/if}
					</div>
				</div>

				<!-- Notes Card (if any) -->
				{#if project.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">{project.notes}</p>
						</div>
					</div>
				{/if}

				<!-- Project 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">Project Scope</h2>
							{#if scope.description}
								<p class="mt-1 text-sm text-theme-muted">{scope.description}</p>
							{/if}
						</div>
						<div class="p-4">
							{#if scope.projectAreas && scope.projectAreas.length > 0}
								<div class="space-y-2">
									{#each [...scope.projectAreas].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.projectTasks && area.projectTasks.length > 0}
														<ul class="space-y-1.5">
															{#each [...area.projectTasks].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>
																	{#if task.estimatedMinutes}
																		<span
																			class="shrink-0 rounded bg-black/5 px-1.5 py-0.5 text-xs text-theme-muted dark:bg-white/10"
																		>
																			~{task.estimatedMinutes} min
																		</span>
																	{/if}
																</li>
															{/each}
														</ul>
													{:else}
														<p class="text-sm text-theme-muted">No tasks in this category.</p>
													{/if}
												</div>
											{/if}
										</div>
									{/each}
								</div>
							{:else}
								<p class="text-sm text-theme-muted">No scope 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">Project not found.</p>
			</div>
		{/if}
	</ContentContainer>
</div>
