<script lang="ts">
	import type { PageData } from './$types';
	import { ContentContainer } from '$lib/components/layout';
	import { CustomerDashboardHeader } from '$lib/components/customer';
	import { IconChevronRight } from '$lib/components/icons';
	import { beforeNavigate } from '$app/navigation';

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

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

	beforeNavigate(({ to }) => {
		if (
			to?.url.pathname.startsWith('/customer/schedule/service/') ||
			to?.url.pathname.startsWith('/customer/schedule/project/')
		) {
			const parts = to.url.pathname.split('/');
			loadingId = parts[parts.length - 1];
		}
	});

	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 display
	let upcomingServices = $derived(
		[...scheduledServices, ...inProgressServices].sort((a, b) =>
			(a.date ?? '').localeCompare(b.date ?? '')
		)
	);
	let upcomingProjects = $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 location name for services
	function getServiceLocation(service: (typeof upcomingServices)[number]): string {
		return service.accountAddress?.name || service.accountAddress?.city || 'Unknown Location';
	}

	// Get account name for services
	function getServiceAccount(service: (typeof upcomingServices)[number]): string {
		return service.account?.name || 'Unknown Account';
	}
</script>

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

<div class="py-8">
	<ContentContainer maxWidth="4xl">
		<CustomerDashboardHeader
			title="Welcome Back"
			subtitle="Here's what's happening with your service accounts."
		/>

		<!-- Quick Stats -->
		<div class="mb-6 grid grid-cols-2 gap-3 sm:grid-cols-4">
			<div class="shadow-theme-sm rounded-xl border border-theme bg-theme-card p-4 text-center">
				<p class="text-2xl font-bold text-primary-600 dark:text-primary-400">
					{data.accounts?.length ?? 0}
				</p>
				<p class="text-xs text-theme-muted">Accounts</p>
			</div>
			<div class="shadow-theme-sm rounded-xl border border-theme bg-theme-card p-4 text-center">
				<p class="text-2xl font-bold text-accent-600 dark:text-accent-400">
					{scheduledServices.length + scheduledProjects.length}
				</p>
				<p class="text-xs text-theme-muted">Scheduled</p>
			</div>
			<div class="shadow-theme-sm rounded-xl border border-theme bg-theme-card p-4 text-center">
				<p class="text-2xl font-bold text-warning-600 dark:text-warning-400">
					{inProgressServices.length + inProgressProjects.length}
				</p>
				<p class="text-xs text-theme-muted">In Progress</p>
			</div>
			<div class="shadow-theme-sm rounded-xl border border-theme bg-theme-card p-4 text-center">
				<p class="text-2xl font-bold text-success-600 dark:text-success-400">
					{(data.services?.completed?.length ?? 0) + (data.projects?.completed?.length ?? 0)}
				</p>
				<p class="text-xs text-theme-muted">Completed</p>
			</div>
		</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="/customer/schedule"
							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">
					{#if upcomingServices.length === 0}
						<p class="py-6 text-center text-sm text-theme-muted italic">No services scheduled</p>
					{:else}
						<div class="space-y-2">
							{#each upcomingServices.slice(0, 5) as service (service.id)}
								<a
									href="/customer/schedule/service/{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">
											{getServiceAccount(service)}
										</p>
										<p class="truncate text-xs text-theme-muted">
											{getServiceLocation(service)}
										</p>
									</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}
										<IconChevronRight
											class="h-5 w-5 shrink-0 text-theme-muted transition-transform group-hover:translate-x-0.5 group-hover:text-secondary-500"
										/>
									{/if}
								</a>
							{/each}
						</div>
						{#if upcomingServices.length > 5}
							<p class="mt-3 text-center text-xs text-theme-muted">
								+{upcomingServices.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="/customer/schedule"
							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">
					{#if upcomingProjects.length === 0}
						<p class="py-6 text-center text-sm text-theme-muted italic">No projects scheduled</p>
					{:else}
						<div class="space-y-2">
							{#each upcomingProjects.slice(0, 5) as project (project.id)}
								<a
									href="/customer/schedule/project/{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">
											{project.name}
										</p>
										<p class="truncate text-xs text-theme-muted">
											{project.customer?.name ?? 'Unknown Customer'}
										</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}
										<IconChevronRight
											class="h-5 w-5 shrink-0 text-theme-muted transition-transform group-hover:translate-x-0.5 group-hover:text-accent-500"
										/>
									{/if}
								</a>
							{/each}
						</div>
						{#if upcomingProjects.length > 5}
							<p class="mt-3 text-center text-xs text-theme-muted">
								+{upcomingProjects.length - 5} more projects
							</p>
						{/if}
					{/if}
				</div>
			</div>
		</div>

		<!-- Quick Links -->
		<section class="mt-6">
			<h2 class="mb-3 text-lg font-semibold text-theme">Quick Links</h2>
			<div class="grid grid-cols-2 gap-3">
				<a
					href="/customer/accounts"
					class="shadow-theme-sm flex items-center gap-3 rounded-xl border border-theme bg-theme-card p-4 transition-all hover:border-primary-500/30 hover:shadow-theme-md"
				>
					<div
						class="flex h-10 w-10 items-center justify-center rounded-lg bg-primary-100 dark:bg-primary-900/50"
					>
						<svg
							class="h-5 w-5 text-primary-600 dark:text-primary-400"
							fill="none"
							stroke="currentColor"
							viewBox="0 0 24 24"
						>
							<path
								stroke-linecap="round"
								stroke-linejoin="round"
								stroke-width="1.5"
								d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4"
							/>
						</svg>
					</div>
					<span class="font-medium text-theme">View Accounts</span>
				</a>
				<a
					href="/customer/history"
					class="shadow-theme-sm flex items-center gap-3 rounded-xl border border-theme bg-theme-card p-4 transition-all hover:border-accent-500/30 hover:shadow-theme-md"
				>
					<div
						class="flex h-10 w-10 items-center justify-center rounded-lg bg-accent-100 dark:bg-accent-900/50"
					>
						<svg
							class="h-5 w-5 text-accent-600 dark:text-accent-400"
							fill="none"
							stroke="currentColor"
							viewBox="0 0 24 24"
						>
							<path
								stroke-linecap="round"
								stroke-linejoin="round"
								stroke-width="1.5"
								d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"
							/>
						</svg>
					</div>
					<span class="font-medium text-theme">View History</span>
				</a>
			</div>
		</section>
	</ContentContainer>
</div>
