<script lang="ts">
	import type { PageData } from './$types';
	import { ContentContainer } from '$lib/components/layout';
	import { PageHeader } from '$lib/components/admin';

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

	let account = $derived(data.account);
	let location = $derived(data.location);

	// Get active labor rate
	let activeLabor = $derived(location.labor.find((l) => l.isActive) ?? location.labor[0] ?? null);

	// Get active schedules
	let activeSchedules = $derived(location.schedules.filter((s) => s.isActive));

	// Get active scopes
	let activeScopes = $derived(location.scopes.filter((s) => s.isActive));

	function formatCurrency(amount: string | number): string {
		const num = typeof amount === 'string' ? parseFloat(amount) : amount;
		return new Intl.NumberFormat('en-US', {
			style: 'currency',
			currency: 'USD',
			minimumFractionDigits: 2
		}).format(num);
	}

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

	function formatFrequency(freq: string): string {
		switch (freq) {
			case 'DAILY':
				return 'Daily';
			case 'WEEKLY':
				return 'Weekly';
			case 'BI_WEEKLY':
				return 'Bi-Weekly';
			case 'MONTHLY':
				return 'Monthly';
			case 'QUARTERLY':
				return 'Quarterly';
			case 'ANNUALLY':
				return 'Annually';
			case 'AS_NEEDED':
				return 'As Needed';
			default:
				return freq;
		}
	}

	function getFrequencyBadgeClass(freq: string): string {
		switch (freq) {
			case 'DAILY':
				return 'bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400';
			case 'WEEKLY':
				return 'bg-primary-100 text-primary-800 dark:bg-primary-900/30 dark:text-primary-400';
			case 'BI_WEEKLY':
				return 'bg-secondary-100 text-secondary-800 dark:bg-secondary-900/30 dark:text-secondary-400';
			case 'MONTHLY':
				return 'bg-accent-100 text-accent-800 dark:bg-accent-900/30 dark:text-accent-400';
			case 'QUARTERLY':
				return 'bg-accent2-100 text-accent2-800 dark:bg-accent2-900/30 dark:text-accent2-400';
			case 'ANNUALLY':
				return 'bg-accent3-100 text-accent3-800 dark:bg-accent3-900/30 dark:text-accent3-400';
			case 'AS_NEEDED':
				return 'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-300';
			default:
				return 'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-300';
		}
	}

	const dayNames = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
	const dayKeys = [
		'monday',
		'tuesday',
		'wednesday',
		'thursday',
		'friday',
		'saturday',
		'sunday'
	] as const;
</script>

<svelte:head>
	<title>{location.name ?? formatAddress()} - {account.name} - Nexus</title>
</svelte:head>

<div class="py-8">
	<ContentContainer>
		<PageHeader
			title={location.name ?? 'Location'}
			subtitle={formatAddress()}
			backHref="/team/accounts/{account.id}"
			colorScheme="primary"
		/>

		<div class="space-y-6">
			<!-- Labor Rate Section -->
			<section
				class="overflow-hidden rounded-xl border border-primary-500/20 bg-theme-card shadow-theme-md"
			>
				<div class="section-header-primary px-6 py-4">
					<h2 class="text-lg font-semibold text-theme">Labor Rate</h2>
				</div>
				<div class="p-6">
					{#if activeLabor}
						<div class="flex items-baseline gap-2">
							<span class="text-3xl font-bold text-primary-600 dark:text-primary-400">
								{formatCurrency(activeLabor.amount)}
							</span>
							<span class="text-theme-secondary">per service</span>
						</div>
						{#if activeLabor.startDate}
							<p class="mt-2 text-sm text-theme-muted">
								Effective from {new Date(activeLabor.startDate + 'T00:00:00').toLocaleDateString(
									'en-US',
									{
										month: 'short',
										day: 'numeric',
										year: 'numeric'
									}
								)}
							</p>
						{/if}
					{:else}
						<p class="text-theme-muted">No labor rate configured</p>
					{/if}
				</div>
			</section>

			<!-- Schedule Section -->
			<section
				class="overflow-hidden rounded-xl border border-primary-500/20 bg-theme-card shadow-theme-md"
			>
				<div class="section-header-primary px-6 py-4">
					<h2 class="text-lg font-semibold text-theme">Schedule</h2>
				</div>
				<div class="p-6">
					{#if activeSchedules.length > 0}
						<div class="space-y-4">
							{#each activeSchedules as schedule (schedule.id)}
								<div class="rounded-lg border border-theme bg-theme-secondary p-4">
									{#if schedule.name}
										<h3 class="mb-3 font-medium text-theme">{schedule.name}</h3>
									{/if}

									<!-- Days of the week -->
									<div class="flex flex-wrap gap-2">
										{#each dayKeys as day, i}
											<span
												class="rounded px-3 py-1.5 text-sm font-medium {schedule[day]
													? 'bg-primary-500/20 text-primary-600 dark:text-primary-400'
													: 'bg-gray-100 text-gray-400 dark:bg-gray-800 dark:text-gray-600'}"
											>
												{dayNames[i]}
											</span>
										{/each}
									</div>

									{#if schedule.weekendService}
										<p class="mt-3 text-sm text-theme-secondary">
											<span class="inline-flex items-center gap-1">
												<svg
													class="h-4 w-4 text-primary-500"
													fill="currentColor"
													viewBox="0 0 20 20"
												>
													<path
														fill-rule="evenodd"
														d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z"
														clip-rule="evenodd"
													/>
												</svg>
												Weekend service available
											</span>
										</p>
									{/if}

									{#if schedule.scheduleException}
										<p class="mt-2 text-sm text-theme-muted">
											<span class="font-medium">Note:</span>
											{schedule.scheduleException}
										</p>
									{/if}
								</div>
							{/each}
						</div>
					{:else}
						<p class="text-theme-muted">No schedule configured</p>
					{/if}
				</div>
			</section>

			<!-- Scope Section -->
			<section
				class="overflow-hidden rounded-xl border border-primary-500/20 bg-theme-card shadow-theme-md"
			>
				<div class="section-header-primary px-6 py-4">
					<h2 class="text-lg font-semibold text-theme">Scope of Work</h2>
				</div>
				<div class="p-6">
					{#if activeScopes.length > 0}
						<div class="space-y-6">
							{#each activeScopes as scope (scope.id)}
								<div
									class="rounded-lg border border-primary-500/20 bg-gradient-to-br from-primary-500/5 to-primary-500/10 p-5 text-sm shadow-sm dark:from-primary-500/10 dark:to-primary-500/5"
								>
									<h3 class="text-base font-bold text-primary-700 dark:text-primary-300">
										{scope.name}
									</h3>
									{#if scope.description}
										<p class="mt-1 text-sm text-theme-secondary">{scope.description}</p>
									{/if}

									{#if scope.areas.length > 0}
										<div class="mt-4 space-y-2">
											{#each scope.areas.sort((a, b) => a.order - b.order) as area (area.id)}
												<details
													class="group rounded-lg border border-primary-500/20 bg-theme-secondary"
												>
													<summary
														class="flex cursor-pointer list-none items-center justify-between px-4 py-3"
													>
														<h4 class="area-title">{area.name}</h4>
														<span class="flex items-center gap-2">
															<span class="text-xs text-theme-muted">
																{area.tasks.length} task{area.tasks.length !== 1 ? 's' : ''}
															</span>
															<svg
																class="h-5 w-5 text-theme-muted transition-transform group-open:rotate-180"
																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>
														</span>
													</summary>

													{#if area.tasks.length > 0}
														<div class="space-y-2 px-4 pb-4">
															{#each area.tasks.sort((a, b) => a.order - b.order) as task (task.id)}
																<div class="task-container">
																	<div class="flex items-start justify-between gap-2">
																		<p class="text-sm text-theme">{task.checklistDescription}</p>
																		<span
																			class="shrink-0 rounded-full px-2 py-0.5 text-xs font-medium {getFrequencyBadgeClass(
																				task.frequency
																			)}"
																		>
																			{formatFrequency(task.frequency)}
																		</span>
																	</div>
																	{#if task.estimatedMinutes}
																		<p class="mt-1 text-xs text-theme-muted">
																			Est. {task.estimatedMinutes} min
																		</p>
																	{/if}
																</div>
															{/each}
														</div>
													{/if}
												</details>
											{/each}
										</div>
									{/if}
								</div>
							{/each}
						</div>
					{:else}
						<p class="text-theme-muted">No scope of work configured</p>
					{/if}
				</div>
			</section>
		</div>
	</ContentContainer>
</div>
