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

	// 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('/admin/services/') ||
			to?.url.pathname.startsWith('/admin/projects/') ||
			to?.url.pathname.startsWith('/admin/invoices/')
		) {
			const parts = to.url.pathname.split('/');
			loadingId = parts[parts.length - 1];
		}
	});

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

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

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

	// Dashboard data - now directly arrays from parent data filtering
	let scheduledServices = $derived(data.dashboard?.services?.scheduled ?? []);
	let inProgressServices = $derived(data.dashboard?.services?.inProgress ?? []);
	let scheduledProjects = $derived(data.dashboard?.projects?.scheduled ?? []);
	let inProgressProjects = $derived(data.dashboard?.projects?.inProgress ?? []);
	let pendingInvoices = $derived(data.dashboard?.invoices ?? []);

	// 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): 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 for services
	function getAccountInfo(accountAddressId: string | null | undefined) {
		if (!accountAddressId || !accountLookup) return null;
		return accountLookup.get(accountAddressId) ?? null;
	}

	// Get project display name
	function getProjectDisplayName(project: {
		accountAddressId?: string | null;
		customerId?: string | null;
		name: string;
	}) {
		if (project.accountAddressId && accountLookup) {
			return accountLookup.get(project.accountAddressId)?.accountName ?? 'Unknown Account';
		}
		if (project.customerId && customerLookup) {
			return customerLookup.get(project.customerId)?.customerName ?? 'Unknown Customer';
		}
		return 'No account/customer';
	}

	// Get customer name for invoices
	function getCustomerName(customerId: string | null | undefined): string {
		if (!customerId || !customerLookup) return 'Unknown Customer';
		return customerLookup.get(customerId)?.customerName ?? 'Unknown Customer';
	}
</script>

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

<div class="py-8">
	<ContentContainer>
		<!-- Welcome Header with nav menu -->
		<AdminDashboardHeader
			title="Welcome back, {firstName}!"
			subtitle="Here's your business overview for this week."
			showBackButton={false}
		/>

		<!-- Quick Actions Row -->
		<div class="mb-6 grid grid-cols-2 gap-3 sm:grid-cols-4">
			<a
				href="/admin/customers?action=create"
				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="customers" class="h-5 w-5 text-primary-600 dark:text-primary-400" />
				</div>
				<span class="text-xs font-medium text-theme sm:text-sm">Add Customer</span>
			</a>
			<a
				href="/admin/accounts?action=create"
				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">Add Account</span>
			</a>
			<a
				href="/admin/services?action=create"
				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">Schedule Service</span>
			</a>
			<a
				href="/admin/invoices?action=create"
				class="flex flex-col items-center gap-2 rounded-xl border border-theme bg-theme-card p-4 transition-all hover:border-accent6-500/30 hover:shadow-md"
			>
				<div
					class="flex h-10 w-10 items-center justify-center rounded-full bg-accent6-100 dark:bg-accent6-900/30"
				>
					<NavIcon name="invoices" class="h-5 w-5 text-accent6-600 dark:text-accent6-400" />
				</div>
				<span class="text-xs font-medium text-theme sm:text-sm">Create Invoice</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="/admin/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)}
								{@const accountInfo = getAccountInfo(service.accountAddressId)}
								<a
									href="/admin/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>
									<!-- 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="/admin/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="/admin/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>

			<!-- Invoices Section -->
			<div class="overflow-hidden card">
				<div class="section-header-accent6 px-3 py-3 sm:px-4 sm:py-4">
					<div class="flex items-center justify-between">
						<h2 class="text-lg font-semibold text-accent6-600 dark:text-accent6-400">Invoices</h2>
						<a
							href="/admin/invoices"
							class="text-sm text-accent6-500 hover:text-accent6-600 dark:hover:text-accent6-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">Awaiting Payment</h3>
					{#if pendingInvoices.length === 0}
						<p class="text-sm text-theme-muted italic">No outstanding invoices</p>
					{:else}
						<div class="space-y-2">
							{#each pendingInvoices.slice(0, 5) as invoice (invoice.id)}
								<a
									href="/admin/invoices/{invoice.id}"
									class="group flex items-center gap-3 overflow-hidden rounded-lg border border-transparent bg-theme-secondary p-2 transition-all hover:border-accent6-500/30 hover:shadow-md"
								>
									<!-- Invoice icon -->
									<div
										class="flex h-11 w-11 shrink-0 items-center justify-center rounded-lg border border-theme bg-theme-card"
									>
										<NavIcon name="invoices" class="h-5 w-5 text-accent6-500" />
									</div>
									<!-- Info -->
									<div class="min-w-0 flex-1 overflow-hidden">
										<p class="truncate text-sm font-medium text-theme">
											{getCustomerName(invoice.customerId)}
										</p>
										<p class="truncate text-xs text-theme-muted">Due {invoice.endDate}</p>
									</div>
									<!-- Status badge -->
									<span
										class="shrink-0 rounded-full bg-accent6-100 px-2 py-0.5 text-[10px] font-medium text-accent6-700 dark:bg-accent6-900/30 dark:text-accent6-400"
									>
										Sent
									</span>
									<!-- Chevron or Spinner -->
									{#if loadingId === invoice.id}
										<svg
											class="h-5 w-5 shrink-0 animate-spin text-accent6-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-accent6-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 pendingInvoices.length > 5}
							<p class="mt-3 text-center text-xs text-theme-muted">
								+{pendingInvoices.length - 5} more outstanding invoices
							</p>
						{/if}
					{/if}
				</div>
			</div>

			<!-- Calendar Section -->
			<div class="overflow-hidden card">
				<div class="section-header-accent7 px-3 py-3 sm:px-4 sm:py-4">
					<div class="flex items-center justify-between">
						<h2 class="text-lg font-semibold text-accent7-600 dark:text-accent7-400">Calendar</h2>
						<a
							href="/admin/calendar"
							class="text-sm text-accent7-500 hover:text-accent7-600 dark:hover:text-accent7-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">Upcoming Events</h3>
					<div class="flex flex-col items-center justify-center py-8 text-center">
						<div
							class="mb-3 flex h-12 w-12 items-center justify-center rounded-full bg-accent7-100 dark:bg-accent7-900/30"
						>
							<NavIcon name="calendar" class="h-6 w-6 text-accent7-500" />
						</div>
						<p class="text-sm text-theme-muted">View your calendar for upcoming events</p>
						<a
							href="/admin/calendar"
							class="mt-3 text-sm font-medium text-accent7-500 hover:text-accent7-600 dark:hover:text-accent7-400"
						>
							Open Calendar
						</a>
					</div>
				</div>
			</div>
		</div>
	</ContentContainer>
</div>
