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

	type Project = TeamDashboard$result['teamDashboard']['projects'][number];
	type Service = TeamDashboard$result['teamDashboard']['services'][number];

	// Track which item is currently loading
	let loadingId = $state<string | null>(null);

	// Listen for navigation to set loading state
	beforeNavigate(({ to }) => {
		if (
			to?.url.pathname.startsWith('/team/services/') ||
			to?.url.pathname.startsWith('/team/projects/')
		) {
			// Extract the ID from the URL
			const parts = to.url.pathname.split('/');
			loadingId = parts[parts.length - 1];
		}
	});

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

	// User info
	let user = $derived(data.user?.data?.me);
	let firstName = $derived(user?.fullName?.split(' ')[0] ?? 'there');

	// Lookups
	let accountLookup = $derived(data.accountLookup);
	let customerLookup = $derived(data.customerLookup);

	// Services data - now flat arrays
	let scheduledServices = $derived(data.services.scheduled ?? []);
	let inProgressServices = $derived(data.services.inProgress ?? []);
	let completedServices = $derived(data.services.completed ?? []);

	// Projects data - now flat arrays
	let scheduledProjects = $derived(data.projects.scheduled ?? []);
	let inProgressProjects = $derived(data.projects.inProgress ?? []);
	let completedProjects = $derived(data.projects.completed ?? []);

	// Get current week bounds (Monday to Sunday) - returns timestamp numbers for comparison
	function getWeekBounds(): { start: number; end: number } {
		const now = new Date();
		const day = now.getDay();
		const diff = day === 0 ? -6 : 1 - day; // Monday = start
		const monday = new Date(now.getFullYear(), now.getMonth(), now.getDate() + diff);
		const sunday = new Date(
			monday.getFullYear(),
			monday.getMonth(),
			monday.getDate() + 6,
			23,
			59,
			59,
			999
		);
		return { start: monday.getTime(), end: sunday.getTime() };
	}

	// Filter services for this week (flat list, sorted by date)
	let thisWeekServices = $derived.by(() => {
		const { start, end } = getWeekBounds();
		const allActive = [...scheduledServices, ...inProgressServices];
		return allActive
			.filter((service) => {
				const d = new Date(service.date + 'T00:00:00').getTime();
				return d >= start && d <= end;
			})
			.sort((a, b) => a.date.localeCompare(b.date));
	});

	// Recently completed services (first 5)
	let recentlyCompletedServices = $derived(completedServices.slice(0, 5));

	// Filter projects for this week (flat list, sorted by date)
	let thisWeekProjects = $derived.by(() => {
		const { start, end } = getWeekBounds();
		const allActive = [...scheduledProjects, ...inProgressProjects];
		return allActive
			.filter((project) => {
				const d = new Date(project.date + 'T00:00:00').getTime();
				return d >= start && d <= end;
			})
			.sort((a, b) => a.date.localeCompare(b.date));
	});

	// Recently completed projects (first 5)
	let recentlyCompletedProjects = $derived(completedProjects.slice(0, 5));

	// Get day number from date
	function getDayNum(dateStr: string): number {
		return new Date(dateStr + 'T00:00:00').getDate();
	}

	// Get short weekday from date
	function getWeekday(dateStr: string): string {
		return new Date(dateStr + 'T00:00:00').toLocaleDateString('en-US', { weekday: 'short' });
	}

	// Get account info
	function getAccountInfo(accountAddressId: string | null | undefined) {
		if (!accountAddressId) return null;
		return accountLookup.get(accountAddressId) ?? null;
	}

	// Get project display name
	function getProjectDisplayName(project: Project) {
		if (project.accountAddressId) {
			return accountLookup.get(project.accountAddressId)?.accountName ?? 'Unknown Account';
		}
		if (project.customerId) {
			return customerLookup.get(project.customerId)?.customerName ?? 'Unknown Customer';
		}
		return 'No account/customer';
	}
</script>

<svelte:head>
	<title>Dashboard - Nexus</title>
</svelte:head>

<div class="py-8">
	<ContentContainer>
		<!-- Welcome Header -->
		<TeamPageHeader title="Welcome back, {firstName}!" showBackButton={false} showNavMenu={true}>
			{#snippet subtitleSnippet({ toggleMenu })}
				Here's your weekly snapshot. Use the <button
					type="button"
					onclick={toggleMenu}
					class="menu-trigger text-primary-500 underline underline-offset-2 hover:text-primary-600 dark:hover:text-primary-400"
					>menu</button
				> or bottom nav to access your work.
			{/snippet}
		</TeamPageHeader>

		<!-- Getting Started Guide -->
		<div class="mb-6 space-y-3">
			<!-- Step 1 -->
			<div class="card-padded">
				<div class="flex items-start gap-4">
					<div
						class="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-primary-500 text-sm font-bold text-white"
					>
						1
					</div>
					<div class="min-w-0">
						<h2 class="text-base font-semibold text-theme">Find Your Assigned Work</h2>
						<p class="text-sm text-theme-secondary">
							Browse your assigned <a
								href="/team/services"
								class="text-secondary-500 underline underline-offset-2 hover:text-secondary-600 dark:hover:text-secondary-400"
								>services</a
							>
							and
							<a
								href="/team/projects"
								class="text-accent-500 underline underline-offset-2 hover:text-accent-600 dark:hover:text-accent-400"
								>projects</a
							>. Use the month filter to find work scheduled for a specific time period.
						</p>
					</div>
				</div>
			</div>

			<!-- Step 2 -->
			<div class="card-padded">
				<div class="flex items-start gap-4">
					<div
						class="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-primary-500 text-sm font-bold text-white"
					>
						2
					</div>
					<div class="min-w-0">
						<h2 class="text-base font-semibold text-theme">Log Your Completed Work</h2>
						<p class="text-sm text-theme-secondary">
							Open a service or project to start a new session. Record the tasks you've completed
							and any notes about the work performed.
						</p>
					</div>
				</div>
			</div>

			<!-- Step 3 -->
			<div class="card-padded">
				<div class="flex items-start gap-4">
					<div
						class="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-primary-500 text-sm font-bold text-white"
					>
						3
					</div>
					<div class="min-w-0">
						<h2 class="text-base font-semibold text-theme">Review Your Reports</h2>
						<p class="text-sm text-theme-secondary">
							At the end of each month, your completed work is summarized into a <a
								href="/team/reports"
								class="text-accent2-500 underline underline-offset-2 hover:text-accent2-600 dark:hover:text-accent2-400"
								>report</a
							>. View your labor totals and payment breakdowns.
						</p>
					</div>
				</div>
			</div>
		</div>

		<!-- Dashboard Grid -->
		<div class="grid grid-cols-1 gap-4 overflow-hidden sm:grid-cols-2 sm:gap-6">
			<!-- Services Section -->
			<div class="overflow-hidden card">
				<div class="section-header-secondary px-3 py-3 sm:px-4 sm:py-4">
					<div class="flex items-center justify-between">
						<h2 class="text-lg font-semibold text-secondary-600 dark:text-secondary-400">
							Services
						</h2>
						<a
							href="/team/services"
							class="text-sm text-secondary-500 hover:text-secondary-600 dark:hover:text-secondary-400"
							>View all</a
						>
					</div>
				</div>

				<div class="divide-theme divide-y">
					<!-- This Week's Services -->
					<div class="px-3 py-3 sm:p-4">
						<h3 class="mb-3 text-sm font-medium text-theme-secondary">This Week</h3>
						{#if thisWeekServices.length === 0}
							<p class="text-sm text-theme-muted italic">No services scheduled this week</p>
						{:else}
							<div class="space-y-2">
								{#each thisWeekServices as service (service.id)}
									{@const accountInfo = getAccountInfo(service.accountAddressId)}
									<a
										href="/team/services/{service.id}"
										class="group flex items-center gap-3 overflow-hidden rounded-lg border border-transparent bg-theme-secondary p-2 transition-all hover:border-secondary-500/30 hover:shadow-md"
									>
										<!-- Calendar tile -->
										<div
											class="flex h-11 w-11 shrink-0 flex-col items-center justify-center rounded-lg border border-theme bg-theme-card"
										>
											<span class="text-[10px] font-medium text-theme-muted uppercase"
												>{getWeekday(service.date)}</span
											>
											<span class="text-base leading-none font-bold text-theme"
												>{getDayNum(service.date)}</span
											>
										</div>
										<!-- Info -->
										<div class="min-w-0 flex-1 overflow-hidden">
											{#if accountInfo}
												<p class="truncate text-sm font-medium text-theme">
													{accountInfo.accountName}
												</p>
												<p class="truncate text-xs text-theme-muted">{accountInfo.addressName}</p>
											{:else}
												<p class="text-sm text-theme-muted italic">No account linked</p>
											{/if}
										</div>
										<!-- Chevron or Spinner -->
										{#if loadingId === service.id}
											<svg
												class="h-5 w-5 shrink-0 animate-spin text-secondary-500"
												style="fill: none"
												viewBox="0 0 24 24"
											>
												<circle
													class="opacity-25"
													cx="12"
													cy="12"
													r="10"
													stroke="currentColor"
													stroke-width="4"
												></circle>
												<path
													class="opacity-75"
													fill="currentColor"
													d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
												></path>
											</svg>
										{:else}
											<svg
												class="h-5 w-5 shrink-0 text-theme-muted transition-transform group-hover:translate-x-0.5 group-hover:text-secondary-500"
												style="fill: none"
												stroke="currentColor"
												viewBox="0 0 24 24"
											>
												<path
													stroke-linecap="round"
													stroke-linejoin="round"
													stroke-width="2"
													d="M9 5l7 7-7 7"
												/>
											</svg>
										{/if}
									</a>
								{/each}
							</div>
						{/if}
					</div>

					<!-- Recently Completed Services -->
					<div class="px-3 py-3 sm:p-4">
						<h3 class="mb-3 text-sm font-medium text-theme-secondary">Recently Completed</h3>
						{#if recentlyCompletedServices.length === 0}
							<p class="text-sm text-theme-muted italic">No completed services yet</p>
						{:else}
							<div class="space-y-2">
								{#each recentlyCompletedServices as service (service.id)}
									{@const accountInfo = getAccountInfo(service.accountAddressId)}
									<a
										href="/team/services/{service.id}"
										class="group flex items-center gap-3 overflow-hidden rounded-lg p-2 transition-colors hover:bg-theme-secondary"
									>
										<!-- Calendar tile -->
										<div
											class="flex h-11 w-11 shrink-0 flex-col items-center justify-center rounded-lg border border-theme bg-theme-secondary"
										>
											<span class="text-[10px] font-medium text-theme-muted uppercase"
												>{getWeekday(service.date)}</span
											>
											<span class="text-base leading-none font-bold text-theme"
												>{getDayNum(service.date)}</span
											>
										</div>
										<!-- Info -->
										<div class="min-w-0 flex-1 overflow-hidden">
											{#if accountInfo}
												<p class="truncate text-sm text-theme">{accountInfo.accountName}</p>
												<p class="truncate text-xs text-theme-muted">{accountInfo.addressName}</p>
											{:else}
												<p class="text-sm text-theme-muted italic">No account linked</p>
											{/if}
										</div>
										<!-- Chevron or Spinner -->
										{#if loadingId === service.id}
											<svg
												class="h-5 w-5 shrink-0 animate-spin text-secondary-500"
												style="fill: none"
												viewBox="0 0 24 24"
											>
												<circle
													class="opacity-25"
													cx="12"
													cy="12"
													r="10"
													stroke="currentColor"
													stroke-width="4"
												></circle>
												<path
													class="opacity-75"
													fill="currentColor"
													d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
												></path>
											</svg>
										{:else}
											<svg
												class="h-5 w-5 shrink-0 text-theme-muted transition-transform group-hover:translate-x-0.5 group-hover:text-secondary-500"
												style="fill: none"
												stroke="currentColor"
												viewBox="0 0 24 24"
											>
												<path
													stroke-linecap="round"
													stroke-linejoin="round"
													stroke-width="2"
													d="M9 5l7 7-7 7"
												/>
											</svg>
										{/if}
									</a>
								{/each}
							</div>
						{/if}
					</div>
				</div>
			</div>

			<!-- Projects Section -->
			<div class="overflow-hidden card">
				<div class="section-header-accent px-3 py-3 sm:px-4 sm:py-4">
					<div class="flex items-center justify-between">
						<h2 class="text-lg font-semibold text-accent-600 dark:text-accent-400">Projects</h2>
						<a
							href="/team/projects"
							class="text-sm text-accent-500 hover:text-accent-600 dark:hover:text-accent-400"
							>View all</a
						>
					</div>
				</div>

				<div class="divide-theme divide-y">
					<!-- This Week's Projects -->
					<div class="px-3 py-3 sm:p-4">
						<h3 class="mb-3 text-sm font-medium text-theme-secondary">This Week</h3>
						{#if thisWeekProjects.length === 0}
							<p class="text-sm text-theme-muted italic">No projects scheduled this week</p>
						{:else}
							<div class="space-y-2">
								{#each thisWeekProjects as project (project.id)}
									<a
										href="/team/projects/{project.id}"
										class="group flex items-center gap-3 overflow-hidden rounded-lg border border-transparent bg-theme-secondary p-2 transition-all hover:border-accent-500/30 hover:shadow-md"
									>
										<!-- Calendar tile -->
										<div
											class="flex h-11 w-11 shrink-0 flex-col items-center justify-center rounded-lg border border-theme bg-theme-card"
										>
											<span class="text-[10px] font-medium text-theme-muted uppercase"
												>{getWeekday(project.date)}</span
											>
											<span class="text-base leading-none font-bold text-theme"
												>{getDayNum(project.date)}</span
											>
										</div>
										<!-- Info -->
										<div class="min-w-0 flex-1 overflow-hidden">
											<p class="truncate text-sm font-medium text-theme">
												{getProjectDisplayName(project)}
											</p>
											<p class="truncate text-xs text-theme-muted">{project.name}</p>
										</div>
										<!-- Chevron or Spinner -->
										{#if loadingId === project.id}
											<svg
												class="h-5 w-5 shrink-0 animate-spin text-accent-500"
												style="fill: none"
												viewBox="0 0 24 24"
											>
												<circle
													class="opacity-25"
													cx="12"
													cy="12"
													r="10"
													stroke="currentColor"
													stroke-width="4"
												></circle>
												<path
													class="opacity-75"
													fill="currentColor"
													d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
												></path>
											</svg>
										{:else}
											<svg
												class="h-5 w-5 shrink-0 text-theme-muted transition-transform group-hover:translate-x-0.5 group-hover:text-accent-500"
												style="fill: none"
												stroke="currentColor"
												viewBox="0 0 24 24"
											>
												<path
													stroke-linecap="round"
													stroke-linejoin="round"
													stroke-width="2"
													d="M9 5l7 7-7 7"
												/>
											</svg>
										{/if}
									</a>
								{/each}
							</div>
						{/if}
					</div>

					<!-- Recently Completed Projects -->
					<div class="px-3 py-3 sm:p-4">
						<h3 class="mb-3 text-sm font-medium text-theme-secondary">Recently Completed</h3>
						{#if recentlyCompletedProjects.length === 0}
							<p class="text-sm text-theme-muted italic">No completed projects yet</p>
						{:else}
							<div class="space-y-2">
								{#each recentlyCompletedProjects as project (project.id)}
									<a
										href="/team/projects/{project.id}"
										class="group flex items-center gap-3 overflow-hidden rounded-lg p-2 transition-colors hover:bg-theme-secondary"
									>
										<!-- Calendar tile -->
										<div
											class="flex h-11 w-11 shrink-0 flex-col items-center justify-center rounded-lg border border-theme bg-theme-secondary"
										>
											<span class="text-[10px] font-medium text-theme-muted uppercase"
												>{getWeekday(project.date)}</span
											>
											<span class="text-base leading-none font-bold text-theme"
												>{getDayNum(project.date)}</span
											>
										</div>
										<!-- Info -->
										<div class="min-w-0 flex-1 overflow-hidden">
											<p class="truncate text-sm text-theme">{getProjectDisplayName(project)}</p>
											<p class="truncate text-xs text-theme-muted">{project.name}</p>
										</div>
										<!-- Chevron or Spinner -->
										{#if loadingId === project.id}
											<svg
												class="h-5 w-5 shrink-0 animate-spin text-accent-500"
												style="fill: none"
												viewBox="0 0 24 24"
											>
												<circle
													class="opacity-25"
													cx="12"
													cy="12"
													r="10"
													stroke="currentColor"
													stroke-width="4"
												></circle>
												<path
													class="opacity-75"
													fill="currentColor"
													d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
												></path>
											</svg>
										{:else}
											<svg
												class="h-5 w-5 shrink-0 text-theme-muted transition-transform group-hover:translate-x-0.5 group-hover:text-accent-500"
												style="fill: none"
												stroke="currentColor"
												viewBox="0 0 24 24"
											>
												<path
													stroke-linecap="round"
													stroke-linejoin="round"
													stroke-width="2"
													d="M9 5l7 7-7 7"
												/>
											</svg>
										{/if}
									</a>
								{/each}
							</div>
						{/if}
					</div>
				</div>
			</div>
		</div>
	</ContentContainer>
</div>
