<script lang="ts">
	import ContentContainer from '$lib/components/layout/ContentContainer.svelte';
	import TeamPageHeader from '$lib/components/team/TeamPageHeader.svelte';
	import type { PageData } from './$types';
	import type { GetAccount$result } from '$houdini';

	type Account = NonNullable<GetAccount$result['account']>;
	type Schedule = NonNullable<Account['addresses']>[number]['schedules'][number];
	type Scope = NonNullable<Account['addresses']>[number]['scopes'][number];

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

	// Use account from page server load (full data with schedules, scopes, contacts)
	let account = $derived(data.account);

	// Get active schedule (no endDate means active)
	function getActiveSchedule(schedules: Schedule[]): Schedule | null {
		if (schedules.length === 0) return null;
		return schedules.find((s) => !s.endDate) ?? null;
	}

	// Get active scope (isActive = true)
	function getActiveScope(scopes: Scope[]): Scope | null {
		if (scopes.length === 0) return null;
		return scopes.find((s) => s.isActive) ?? null;
	}
</script>

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

<div class="py-8">
	<ContentContainer>
		{#if !account}
			<div class="empty-state p-12">
				<svg class="empty-state-icon" style="fill: none" stroke="currentColor" viewBox="0 0 24 24">
					<path
						stroke-linecap="round"
						stroke-linejoin="round"
						stroke-width="1.5"
						d="M9.172 16.172a4 4 0 015.656 0M9 10h.01M15 10h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
					/>
				</svg>
				<h2 class="empty-state-title">Account Not Found</h2>
				<p class="empty-state-text">
					The account you're looking for doesn't exist or you don't have access to it.
				</p>
				<a href="/team/accounts" class="mt-4 btn-primary">Back to Accounts</a>
			</div>
		{:else}
			<TeamPageHeader title={account.name} colorScheme="primary" backHref="/team/accounts" />

			<div class="grid grid-cols-1 gap-6 lg:grid-cols-3">
				<!-- Main Content: Locations (2 columns on desktop) -->
				<div class="lg:col-span-2">
					<div class="card-padded">
						<h2 class="mb-4 section-title">
							{#if account.addresses && account.addresses.length === 1}
								{account.addresses[0].name || 'Primary Service Address'}
							{:else}
								Locations
							{/if}
						</h2>

						{#if account.addresses && account.addresses.length > 0}
							<div class="space-y-4">
								{#each account.addresses as location (location.id)}
									{@const activeSchedule = getActiveSchedule(location.schedules)}
									{@const activeScope = getActiveScope(location.scopes)}
									{@const locationName = location.name || 'Primary Service Address'}
									<details class="group card-interactive border-2 bg-subtle p-4">
										<summary class="expandable-header items-start gap-3">
											<span class="flex-1 text-left">
												<span class="mb-1 flex items-center gap-2">
													<span class="text-base font-bold text-theme">{locationName}</span>
													{#if location.isPrimary && account.addresses.length > 1}
														<span class="badge-primary py-1">Primary</span>
													{/if}
												</span>
												<span class="block text-sm text-theme-secondary">
													{location.streetAddress}, {location.city}, {location.state}
													{location.zipCode}
												</span>
											</span>
											<svg
												class="expandable-chevron text-theme-secondary"
												style="fill: none"
												stroke="currentColor"
												stroke-width="2.5"
												viewBox="0 0 24 24"
											>
												<path stroke-linecap="round" stroke-linejoin="round" d="M19 9l-7 7-7-7" />
											</svg>
										</summary>

										{#if location.notes}
											<p
												class="mt-3 border-t border-theme pt-3 text-sm text-theme-secondary italic"
											>
												{location.notes}
											</p>
										{/if}

										<!-- Schedule -->
										{#if activeSchedule}
											<div class="mt-4 border-t border-theme pt-4">
												<h4 class="mb-3 text-sm font-semibold text-theme">Schedule</h4>
												<div class="rounded-lg bg-subtle p-3 text-sm">
													<div class="mb-2 flex items-start justify-between">
														<h5 class="font-semibold text-theme">
															{activeSchedule.name || 'Schedule'}
														</h5>
														{#if activeSchedule.scheduleException}
															<span class="badge-warning">{activeSchedule.scheduleException}</span>
														{/if}
													</div>
													<div class="flex flex-wrap gap-1">
														{#if activeSchedule.sundayService}
															<span class="schedule-day">Sun</span>
														{/if}
														{#if activeSchedule.mondayService}
															<span class="schedule-day">Mon</span>
														{/if}
														{#if activeSchedule.tuesdayService}
															<span class="schedule-day">Tue</span>
														{/if}
														{#if activeSchedule.wednesdayService}
															<span class="schedule-day">Wed</span>
														{/if}
														{#if activeSchedule.thursdayService}
															<span class="schedule-day">Thu</span>
														{/if}
														{#if activeSchedule.fridayService}
															<span class="schedule-day">Fri</span>
														{/if}
														{#if activeSchedule.saturdayService}
															<span class="schedule-day">Sat</span>
														{/if}
														{#if activeSchedule.weekendService}
															<span class="schedule-day-weekend">Weekend</span>
														{/if}
													</div>
												</div>
											</div>
										{:else if location.schedules.length > 0}
											<div class="mt-4 border-t border-theme pt-4">
												<h4 class="mb-2 text-sm font-semibold text-theme">Schedule</h4>
												<p class="text-sm text-theme-muted">
													{location.schedules.length} schedule{location.schedules.length === 1
														? ''
														: 's'} (none active)
												</p>
											</div>
										{/if}

										<!-- Scope -->
										{#if activeScope}
											<details class="group/scope mt-4 border-t-2 border-accent-500/20 pt-4">
												<summary
													class="expandable-header text-sm font-bold text-accent-600 hover:text-accent-700 dark:text-accent-400 dark:hover:text-accent-300"
												>
													<span>Scope</span>
													<svg
														class="h-5 w-5 transition-transform group-open/scope:rotate-180"
														style="fill: none"
														stroke="currentColor"
														stroke-width="2.5"
														viewBox="0 0 24 24"
													>
														<path
															stroke-linecap="round"
															stroke-linejoin="round"
															d="M19 9l-7 7-7-7"
														/>
													</svg>
												</summary>

												<div class="mt-4">
													<div class="scope-container">
														<h5 class="mb-1 scope-title">{activeScope.name}</h5>
														{#if activeScope.description}
															<p class="mb-4 text-xs text-theme-secondary">
																{activeScope.description}
															</p>
														{/if}

														{#if activeScope.areas && activeScope.areas.length > 0}
															<div class="mt-4 space-y-3">
																{#each activeScope.areas.toSorted((a, b) => a.order - b.order) as area (area.id)}
																	<details class="group/area area-container">
																		<summary
																			class="expandable-header items-start gap-2 area-title hover:text-primary-700 dark:hover:text-primary-300"
																		>
																			<span class="flex-1 text-left">{area.name}</span>
																			<svg
																				class="h-4 w-4 flex-shrink-0 transition-transform group-open/area:rotate-180"
																				style="fill: none"
																				stroke="currentColor"
																				stroke-width="2.5"
																				viewBox="0 0 24 24"
																			>
																				<path
																					stroke-linecap="round"
																					stroke-linejoin="round"
																					d="M19 9l-7 7-7-7"
																				/>
																			</svg>
																		</summary>

																		{#if area.tasks && area.tasks.length > 0}
																			<div class="mt-3 ml-1 space-y-2">
																				{#each area.tasks.toSorted((a, b) => a.order - b.order) as task (task.id)}
																					<div class="task-container">
																						<p class="mb-1 text-xs leading-relaxed text-theme">
																							{task.checklistDescription || task.description}
																						</p>
																						{#if task.frequency}
																							<p class="mt-2 text-[10px] text-theme-secondary">
																								<span class="font-semibold text-primary-500"
																									>Frequency:</span
																								>
																								{task.frequency.toLowerCase()}
																							</p>
																						{/if}
																					</div>
																				{/each}
																			</div>
																		{/if}
																	</details>
																{/each}
															</div>
														{/if}
													</div>
												</div>
											</details>
										{:else if location.scopes.length > 0}
											<div class="mt-4 border-t border-theme pt-4">
												<h4 class="mb-2 text-sm font-semibold text-theme">Scope of Work</h4>
												<p class="text-sm text-theme-muted">
													{location.scopes.length} scope{location.scopes.length === 1 ? '' : 's'} (none
													active)
												</p>
											</div>
										{/if}
									</details>
								{/each}
							</div>
						{:else}
							<p class="text-sm text-theme-secondary">No locations found.</p>
						{/if}
					</div>
				</div>

				<!-- Sidebar: Contacts (1 column on desktop, stacks on mobile) -->
				<div class="lg:col-span-1">
					<div class="card-padded lg:sticky lg:top-6">
						<h2 class="mb-4 section-title-accent">Contacts</h2>

						{#if account.contacts && account.contacts.length > 0}
							<div class="space-y-4">
								{#each account.contacts.filter((c) => c.isActive) as contact, i (contact.id)}
									<div
										class={i < account.contacts.filter((c) => c.isActive).length - 1
											? 'list-divider'
											: ''}
									>
										<p class="contact-name">
											{contact.fullName}
											{#if contact.isPrimary}
												<span class="ml-2 badge-primary">Primary</span>
											{/if}
										</p>
										{#if contact.email}
											<a href="mailto:{contact.email}" class="contact-email">
												{contact.email}
											</a>
										{/if}
										{#if contact.notes}
											<p class="mt-2 text-sm text-theme-muted italic">{contact.notes}</p>
										{/if}
									</div>
								{/each}
							</div>
						{:else}
							<p class="text-sm text-theme-secondary">No contacts found.</p>
						{/if}
					</div>
				</div>
			</div>
		{/if}
	</ContentContainer>
</div>
