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

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

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

	beforeNavigate(({ to }) => {
		if (
			to?.url.pathname.startsWith('/team/services/') ||
			to?.url.pathname.startsWith('/team/projects/')
		) {
			const parts = to.url.pathname.split('/');
			loadingId = parts[parts.length - 1];
		}
	});

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

	// Dashboard data
	let scheduledServices = $derived(data.services?.scheduled ?? []);
	let scheduledProjects = $derived(data.projects?.scheduled ?? []);
	let inProgressServices = $derived(data.services?.inProgress ?? []);
	let inProgressProjects = $derived(data.projects?.inProgress ?? []);

	// Combine scheduled + in-progress for "this week" view
	let thisWeekServices = $derived(
		[...scheduledServices, ...inProgressServices].sort((a, b) =>
			(a.date ?? '').localeCompare(b.date ?? '')
		)
	);
	let thisWeekProjects = $derived(
		[...scheduledProjects, ...inProgressProjects].sort((a, b) =>
			(a.date ?? '').localeCompare(b.date ?? '')
		)
	);

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

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

	// Get service display info
	function getServiceDisplayName(service: (typeof scheduledServices)[number]): string {
		return service.account?.name ?? 'Unknown Account';
	}

	function getServiceLocation(service: (typeof scheduledServices)[number]): string {
		if (service.accountAddress?.name) return service.accountAddress.name;
		if (service.accountAddress?.city) return service.accountAddress.city;
		return '';
	}

	// Get project display info
	function getProjectDisplayName(project: (typeof scheduledProjects)[number]): string {
		return project.customer?.name ?? 'Unknown Customer';
	}
</script>

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

<div class="py-8">
	<ContentContainer>
		<!-- Welcome Header -->
		<TeamDashboardHeader
			title="Welcome back, {firstName}!"
			subtitle="Here's your work for this week."
			showBackButton={false}
		/>

		<!-- Quick Actions Row -->
		<div class="mb-6 grid grid-cols-4 gap-3">
			<a
				href="/team/accounts"
				class="flex flex-col items-center gap-2 rounded-xl border border-theme bg-theme-card p-4 transition-all hover:border-primary-500/30 hover:shadow-md"
			>
				<div
					class="flex h-10 w-10 items-center justify-center rounded-full bg-primary-100 dark:bg-primary-900/30"
				>
					<NavIcon name="accounts" class="h-5 w-5 text-primary-600 dark:text-primary-400" />
				</div>
				<span class="text-xs font-medium text-theme sm:text-sm">Accounts</span>
			</a>
			<a
				href="/team/services"
				class="flex flex-col items-center gap-2 rounded-xl border border-theme bg-theme-card p-4 transition-all hover:border-secondary-500/30 hover:shadow-md"
			>
				<div
					class="flex h-10 w-10 items-center justify-center rounded-full bg-secondary-100 dark:bg-secondary-900/30"
				>
					<NavIcon name="services" class="h-5 w-5 text-secondary-600 dark:text-secondary-400" />
				</div>
				<span class="text-xs font-medium text-theme sm:text-sm">Services</span>
			</a>
			<a
				href="/team/projects"
				class="flex flex-col items-center gap-2 rounded-xl border border-theme bg-theme-card p-4 transition-all hover:border-accent-500/30 hover:shadow-md"
			>
				<div
					class="flex h-10 w-10 items-center justify-center rounded-full bg-accent-100 dark:bg-accent-900/30"
				>
					<NavIcon name="projects" class="h-5 w-5 text-accent-600 dark:text-accent-400" />
				</div>
				<span class="text-xs font-medium text-theme sm:text-sm">Projects</span>
			</a>
			<a
				href="/team/reports"
				class="flex flex-col items-center gap-2 rounded-xl border border-theme bg-theme-card p-4 transition-all hover:border-accent2-500/30 hover:shadow-md"
			>
				<div
					class="flex h-10 w-10 items-center justify-center rounded-full bg-accent2-100 dark:bg-accent2-900/30"
				>
					<NavIcon name="reports" class="h-5 w-5 text-accent2-600 dark:text-accent2-400" />
				</div>
				<span class="text-xs font-medium text-theme sm:text-sm">Reports</span>
			</a>
		</div>

		<!-- Dashboard Grid -->
		<div class="grid grid-cols-1 gap-4 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="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.slice(0, 5) as service (service.id)}
								<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">
										<p class="truncate text-sm font-medium text-theme">
											{getServiceDisplayName(service)}
										</p>
										{#if getServiceLocation(service)}
											<p class="truncate text-xs text-theme-muted">{getServiceLocation(service)}</p>
										{/if}
									</div>
									<!-- Status badge -->
									<span
										class="shrink-0 rounded-full px-2 py-0.5 text-[10px] font-medium {service.status ===
										'IN_PROGRESS'
											? 'bg-warning-100 text-warning-700 dark:bg-warning-900/30 dark:text-warning-400'
											: 'bg-secondary-100 text-secondary-700 dark:bg-secondary-900/30 dark:text-secondary-400'}"
									>
										{service.status === 'IN_PROGRESS' ? 'Active' : 'Scheduled'}
									</span>
									<!-- 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 thisWeekServices.length > 5}
							<p class="mt-3 text-center text-xs text-theme-muted">
								+{thisWeekServices.length - 5} more services
							</p>
						{/if}
					{/if}
				</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="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.slice(0, 5) 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>
									<!-- Status badge -->
									<span
										class="shrink-0 rounded-full px-2 py-0.5 text-[10px] font-medium {project.status ===
										'IN_PROGRESS'
											? 'bg-warning-100 text-warning-700 dark:bg-warning-900/30 dark:text-warning-400'
											: 'bg-accent-100 text-accent-700 dark:bg-accent-900/30 dark:text-accent-400'}"
									>
										{project.status === 'IN_PROGRESS' ? 'Active' : 'Scheduled'}
									</span>
									<!-- 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 thisWeekProjects.length > 5}
							<p class="mt-3 text-center text-xs text-theme-muted">
								+{thisWeekProjects.length - 5} more projects
							</p>
						{/if}
					{/if}
				</div>
			</div>
		</div>
	</ContentContainer>
</div>
