<script lang="ts">
	import ContentContainer from '$lib/components/layout/ContentContainer.svelte';
	import CustomerPageHeader from '$lib/components/customer/CustomerPageHeader.svelte';
	import MonthSelector from '$lib/components/team/MonthSelector.svelte';
	import { formatDate, getCurrentMonth } from '$lib/utils/date';
	import type { PageData } from './$types';
	import type { CustomerAccountInfo } from './+layout.server';
	import type {
		CustomerAccounts$result,
		CustomerServices$result,
		CustomerProjects$result,
		CustomerInvoices$result
	} from '$houdini';

	type Account = CustomerAccounts$result['accounts'][number];
	type Service = CustomerServices$result['services'][number];
	type Project = CustomerProjects$result['projects'][number];
	type Invoice = CustomerInvoices$result['invoices'][number];

	type LayoutData = PageData & {
		currentMonth?: string;
		accounts?: Account[];
		services?: {
			upcoming?: Service[];
			completed?: Service[];
		};
		projects?: {
			upcoming?: Project[];
			completed?: Project[];
		};
		invoices?: Invoice[];
		customerAccountLookup?: Record<string, CustomerAccountInfo>;
	};

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

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

	// Get data from layout - now flat arrays
	let accounts = $derived(data.accounts ?? []);
	let upcomingServices = $derived(data.services?.upcoming ?? []);
	let upcomingProjects = $derived(data.projects?.upcoming ?? []);
	let completedServices = $derived(data.services?.completed ?? []);
	let completedProjects = $derived(data.projects?.completed ?? []);
	let invoices = $derived(data.invoices ?? []);
	let customerAccountLookup = $derived(
		data.customerAccountLookup ?? ({} as Record<string, CustomerAccountInfo>)
	);

	// Filter by current month
	let monthFilteredUpcomingServices = $derived(
		upcomingServices.filter((s) => s.date.startsWith(currentMonth))
	);
	let monthFilteredUpcomingProjects = $derived(
		upcomingProjects.filter((p) => p.date.startsWith(currentMonth))
	);
	let monthFilteredCompletedServices = $derived(
		completedServices.filter((s) => s.date.startsWith(currentMonth))
	);
	let monthFilteredCompletedProjects = $derived(
		completedProjects.filter((p) => p.date.startsWith(currentMonth))
	);
	let monthFilteredInvoices = $derived(invoices.filter((inv) => inv.date.startsWith(currentMonth)));

	// Compute stats (month-filtered)
	let accountCount = $derived(accounts.length);
	let upcomingCount = $derived(
		monthFilteredUpcomingServices.length + monthFilteredUpcomingProjects.length
	);
	let completedCount = $derived(
		monthFilteredCompletedServices.length + monthFilteredCompletedProjects.length
	);
	let pendingInvoices = $derived(
		monthFilteredInvoices.filter((inv) => inv.status !== 'PAID' && inv.status !== 'CANCELLED')
	);
	let pendingInvoiceCount = $derived(pendingInvoices.length);

	// Build stats array
	let stats = $derived([
		{
			label: 'Active Accounts',
			value: accountCount.toString(),
			colorClass: 'text-primary-600 dark:text-primary-400'
		},
		{
			label: 'Upcoming',
			value: upcomingCount.toString(),
			colorClass: 'text-secondary-600 dark:text-secondary-400'
		},
		{
			label: 'Completed',
			value: completedCount.toString(),
			colorClass: 'text-accent-600 dark:text-accent-400'
		},
		{
			label: 'Pending Invoices',
			value: pendingInvoiceCount.toString(),
			colorClass: 'text-accent6-600 dark:text-accent6-400'
		}
	]);

	// Combine upcoming services and projects, sorted by date
	type UpcomingItem =
		| { type: 'service'; date: string; id: string; accountId: string; accountAddressId: string }
		| {
				type: 'project';
				date: string;
				id: string;
				name: string;
				accountAddressId?: string;
				streetAddress?: string;
				city?: string;
				state?: string;
		  };

	let upcomingItems = $derived.by(() => {
		const items: UpcomingItem[] = [];

		monthFilteredUpcomingServices.forEach((s) => {
			items.push({
				type: 'service',
				date: s.date,
				id: s.id,
				accountId: s.accountId ?? '',
				accountAddressId: s.accountAddressId ?? ''
			});
		});

		monthFilteredUpcomingProjects.forEach((p) => {
			items.push({
				type: 'project',
				date: p.date,
				id: p.id,
				name: p.name,
				accountAddressId: p.accountAddressId ?? undefined,
				streetAddress: p.streetAddress ?? undefined,
				city: p.city ?? undefined,
				state: p.state ?? undefined
			});
		});

		// Sort by date ascending
		items.sort((a, b) => a.date.localeCompare(b.date));

		// Take first 3
		return items.slice(0, 3);
	});

	function getAccountName(accountId: string, addressId: string): string {
		// accountId and addressId from services are already UUIDs, not Relay IDs
		const addrInfo = customerAccountLookup[addressId];
		if (addrInfo) {
			return addrInfo.addressName ? `${addrInfo.name} - ${addrInfo.addressName}` : addrInfo.name;
		}
		const acctInfo = customerAccountLookup[accountId];
		return acctInfo?.name ?? 'Unknown Account';
	}

	function getProjectLocation(item: Extract<UpcomingItem, { type: 'project' }>): string {
		// If project has accountAddressId, get address from lookup
		if (item.accountAddressId) {
			const addrInfo = customerAccountLookup[item.accountAddressId];
			if (addrInfo) {
				return `${addrInfo.streetAddress}, ${addrInfo.city}`;
			}
		}
		// Otherwise use project's own address fields
		return `${item.streetAddress ?? ''}, ${item.city ?? ''}`;
	}

	function getItemHref(item: UpcomingItem): string {
		if (item.type === 'service') {
			return `/customer/schedule/service/${item.id}`;
		}
		return `/customer/schedule/project/${item.id}`;
	}
</script>

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

<div class="py-8">
	<ContentContainer>
		<!-- Welcome Header with Nav Menu -->
		<CustomerPageHeader
			title="Welcome back, {firstName}!"
			subtitle="Here's what's happening with your accounts."
			colorScheme="primary"
			showBackButton={false}
			showNavMenu={true}
		/>

		<!-- Month Selector -->
		<div class="mb-6">
			<MonthSelector value={currentMonth} />
		</div>

		<!-- Stats Overview -->
		<div class="mb-8 grid grid-cols-2 gap-4 lg:grid-cols-4">
			{#each stats as stat (stat.label)}
				<div class="rounded-xl border border-theme bg-theme-card p-4">
					<div class="text-2xl font-bold {stat.colorClass}">
						{stat.value}
					</div>
					<div class="text-sm text-theme-muted">{stat.label}</div>
				</div>
			{/each}
		</div>

		<!-- Content Grid -->
		<div class="mb-8 grid gap-6 md:grid-cols-2">
			<!-- Upcoming Schedule -->
			<div class="overflow-hidden rounded-xl border border-theme bg-theme-card">
				<div class="flex items-center justify-between section-header-secondary px-4 py-3">
					<h2 class="font-semibold text-secondary-700 dark:text-secondary-400">
						Upcoming Schedule
					</h2>
					<a
						href="/customer/schedule"
						class="text-sm text-secondary-600 hover:underline dark:text-secondary-400">View all</a
					>
				</div>
				<div class="divide-theme divide-y">
					{#each upcomingItems as item (item.id)}
						<a
							href={getItemHref(item)}
							class="block px-4 py-3 hover:bg-black/5 dark:hover:bg-white/5"
						>
							<div class="flex items-center justify-between">
								<div class="min-w-0 flex-1">
									{#if item.type === 'service'}
										<p class="text-sm font-medium text-theme">Service</p>
										<p class="truncate text-xs text-theme-muted">
											{getAccountName(item.accountId, item.accountAddressId)}
										</p>
									{:else}
										<p class="text-sm font-medium text-theme">{item.name}</p>
										<p class="truncate text-xs text-theme-muted">
											{getProjectLocation(item)}
										</p>
									{/if}
								</div>
								<span
									class="ml-2 shrink-0 rounded px-2 py-1 text-xs {item.type === 'service'
										? 'bg-secondary-100 text-secondary-700 dark:bg-secondary-900/30 dark:text-secondary-400'
										: 'bg-accent-100 text-accent-700 dark:bg-accent-900/30 dark:text-accent-400'}"
								>
									{formatDate(item.date)}
								</span>
							</div>
						</a>
					{/each}
					{#if upcomingItems.length === 0}
						<div class="px-4 py-8 text-center text-sm text-theme-muted">
							No upcoming services or projects scheduled
						</div>
					{/if}
				</div>
			</div>

			<!-- Pending Invoices -->
			<div class="overflow-hidden rounded-xl border border-theme bg-theme-card">
				<div class="flex items-center justify-between section-header-accent6 px-4 py-3">
					<h2 class="font-semibold text-accent6-700 dark:text-accent6-400">Pending Invoices</h2>
					<a
						href="/customer/invoices"
						class="text-sm text-accent6-600 hover:underline dark:text-accent6-400">View all</a
					>
				</div>
				<div class="divide-theme divide-y">
					{#each pendingInvoices.slice(0, 3) as invoice (invoice.id)}
						<a
							href="/customer/invoices/{invoice.id}"
							class="block px-4 py-3 hover:bg-black/5 dark:hover:bg-white/5"
						>
							<div class="flex items-center justify-between">
								<div class="min-w-0 flex-1">
									<p class="text-sm font-medium text-theme">Invoice - {formatDate(invoice.date)}</p>
									<p class="truncate text-xs text-theme-muted">
										{invoice.status === 'OVERDUE' ? 'Payment overdue' : 'Payment pending'}
									</p>
								</div>
								<span
									class="ml-2 shrink-0 rounded px-2 py-1 text-xs {invoice.status === 'OVERDUE'
										? 'bg-error-100 text-error-700 dark:bg-error-900/30 dark:text-error-400'
										: 'bg-warning-100 text-warning-700 dark:bg-warning-900/30 dark:text-warning-400'}"
								>
									{invoice.status === 'OVERDUE' ? 'Overdue' : 'Pending'}
								</span>
							</div>
						</a>
					{/each}
					{#if pendingInvoices.length === 0}
						<div class="px-4 py-8 text-center text-sm text-theme-muted">No pending invoices</div>
					{/if}
				</div>
			</div>
		</div>

		<!-- Quick Links -->
		<div class="overflow-hidden rounded-xl border border-theme bg-theme-card">
			<div class="section-header-primary px-4 py-3">
				<h2 class="font-semibold text-primary-700 dark:text-primary-400">Quick Links</h2>
			</div>
			<div class="grid grid-cols-2 gap-2 p-4 md:grid-cols-4">
				<a
					href="/customer/accounts"
					class="flex items-center gap-3 rounded-lg p-3 transition-colors hover:bg-black/5 dark:hover:bg-white/5"
				>
					<svg
						class="h-5 w-5 text-primary-500"
						style="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>
						<p class="text-sm font-medium text-theme">Accounts</p>
						<p class="hidden text-xs text-theme-muted sm:block">Service locations</p>
					</div>
				</a>
				<a
					href="/customer/schedule"
					class="flex items-center gap-3 rounded-lg p-3 transition-colors hover:bg-black/5 dark:hover:bg-white/5"
				>
					<svg
						class="h-5 w-5 text-secondary-500"
						style="fill: none"
						stroke="currentColor"
						viewBox="0 0 24 24"
					>
						<path
							stroke-linecap="round"
							stroke-linejoin="round"
							stroke-width="1.5"
							d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"
						/>
					</svg>
					<div>
						<p class="text-sm font-medium text-theme">Schedule</p>
						<p class="hidden text-xs text-theme-muted sm:block">Upcoming work</p>
					</div>
				</a>
				<a
					href="/customer/history"
					class="flex items-center gap-3 rounded-lg p-3 transition-colors hover:bg-black/5 dark:hover:bg-white/5"
				>
					<svg
						class="h-5 w-5 text-accent-500"
						style="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>
						<p class="text-sm font-medium text-theme">History</p>
						<p class="hidden text-xs text-theme-muted sm:block">Completed work</p>
					</div>
				</a>
				<a
					href="/customer/invoices"
					class="flex items-center gap-3 rounded-lg p-3 transition-colors hover:bg-black/5 dark:hover:bg-white/5"
				>
					<svg
						class="h-5 w-5 text-accent6-500"
						style="fill: none"
						stroke="currentColor"
						viewBox="0 0 24 24"
					>
						<path
							stroke-linecap="round"
							stroke-linejoin="round"
							stroke-width="1.5"
							d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"
						/>
					</svg>
					<div>
						<p class="text-sm font-medium text-theme">Invoices</p>
						<p class="hidden text-xs text-theme-muted sm:block">Billing history</p>
					</div>
				</a>
			</div>
		</div>
	</ContentContainer>
</div>
