<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 { navigating } from '$app/state';
	import type { PageData } from './$types';
	import type { CustomerAccountInfo } from '../+layout.server';
	import type { CustomerServices$result, CustomerProjects$result } from '$houdini';

	type Service = CustomerServices$result['services'][number];
	type Project = CustomerProjects$result['projects'][number];

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

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

	let currentMonth = $derived(data.currentMonth ?? getCurrentMonth());
	let upcomingServices = $derived(data.services?.upcoming ?? []);
	let upcomingProjects = $derived(data.projects?.upcoming ?? []);
	let customerAccountLookup = $derived(
		data.customerAccountLookup ?? ({} as Record<string, CustomerAccountInfo>)
	);

	type FilterType = 'all' | 'services' | 'projects';
	let activeFilter = $state<FilterType>('all');

	// Combine and sort items
	type ScheduleItem =
		| {
				type: 'service';
				id: string;
				date: string;
				status: string;
				accountId: string;
				accountAddressId: string;
		  }
		| {
				type: 'project';
				id: string;
				date: string;
				status: string;
				name: string;
				accountAddressId?: string;
				streetAddress?: string;
				city?: string;
				state?: string;
		  };

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

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

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

		return items;
	});

	// Helper to get sortable name for an item
	function getSortName(item: ScheduleItem): string {
		if (item.type === 'service') {
			return getAccountName(item.accountId, item.accountAddressId);
		}
		return item.name;
	}

	// Sort by date ascending, then alphabetically by name
	let sortedItems = $derived(
		[...allItems].sort((a, b) => {
			const dateCompare = a.date.localeCompare(b.date);
			if (dateCompare !== 0) return dateCompare;
			return getSortName(a).localeCompare(getSortName(b));
		})
	);

	// Filter by selected month (client-side)
	let monthFilteredItems = $derived(
		sortedItems.filter((item) => item.date.startsWith(currentMonth))
	);

	let filteredItems = $derived(
		monthFilteredItems.filter((item) => {
			if (activeFilter === 'all') return true;
			if (activeFilter === 'services') return item.type === 'service';
			if (activeFilter === 'projects') return item.type === 'project';
			return true;
		})
	);

	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<ScheduleItem, { 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: ScheduleItem): string {
		if (item.type === 'service') {
			return `/customer/schedule/service/${item.id}`;
		}
		return `/customer/schedule/project/${item.id}`;
	}

	function getStatusBadgeClasses(status: string, type: 'service' | 'project'): string {
		if (status === 'IN_PROGRESS') {
			return 'bg-warning-100 text-warning-700 dark:bg-warning-900/30 dark:text-warning-400';
		}
		if (type === 'service') {
			return 'bg-secondary-100 text-secondary-700 dark:bg-secondary-900/30 dark:text-secondary-400';
		}
		return 'bg-accent-100 text-accent-700 dark:bg-accent-900/30 dark:text-accent-400';
	}

	const filterTabs: { key: FilterType; label: string }[] = [
		{ key: 'all', label: 'All' },
		{ key: 'services', label: 'Services' },
		{ key: 'projects', label: 'Projects' }
	];

	// Check if navigating to a specific item
	function isNavigatingTo(item: ScheduleItem): boolean {
		if (!navigating.to) return false;
		const href = getItemHref(item);
		return navigating.to.url.pathname === href;
	}
</script>

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

<div class="py-8">
	<ContentContainer>
		<CustomerPageHeader
			title="Schedule"
			subtitle="View your upcoming services and projects."
			colorScheme="secondary"
		/>

		<!-- Month Selector and Filter Tabs -->
		<div class="mb-6 flex flex-wrap items-center justify-between gap-4">
			<MonthSelector value={currentMonth} />
			<div class="flex gap-2">
				{#each filterTabs as tab (tab.key)}
					<button
						type="button"
						onclick={() => (activeFilter = tab.key)}
						class="rounded-lg px-4 py-2 text-sm font-medium transition-colors {activeFilter ===
						tab.key
							? 'bg-secondary-500 text-white'
							: 'bg-black/5 text-theme-secondary hover:bg-black/10 dark:bg-white/10 dark:hover:bg-white/15'}"
					>
						{tab.label}
					</button>
				{/each}
			</div>
		</div>

		<!-- Schedule List -->
		{#if filteredItems.length > 0}
			<div class="space-y-3">
				{#each filteredItems as item (item.id)}
					<a
						href={getItemHref(item)}
						class="block {item.type === 'service' ? 'card-service' : 'card-project'}"
					>
						<div class="flex items-center justify-between gap-4">
							<div class="min-w-0 flex-1">
								<div class="mb-1 flex items-center gap-2">
									<span
										class="inline-flex items-center rounded px-1.5 py-0.5 text-xs font-medium {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'}"
									>
										{item.type === 'service' ? 'Service' : 'Project'}
									</span>
									<span class="text-sm font-medium text-theme">
										{formatDate(item.date)}
									</span>
								</div>
								{#if item.type === 'service'}
									<p class="truncate text-sm text-theme-secondary">
										{getAccountName(item.accountId, item.accountAddressId)}
									</p>
								{:else}
									<p class="truncate font-medium text-theme">{item.name}</p>
									<p class="truncate text-sm text-theme-muted">
										{getProjectLocation(item)}
									</p>
								{/if}
							</div>
							<div class="flex shrink-0 items-center gap-2">
								<span
									class="rounded px-2 py-1 text-xs {getStatusBadgeClasses(item.status, item.type)}"
								>
									{item.status === 'IN_PROGRESS' ? 'In Progress' : 'Scheduled'}
								</span>
								{#if isNavigatingTo(item)}
									<svg
										class="h-5 w-5 animate-spin text-theme-muted"
										viewBox="0 0 24 24"
										style="fill: none"
									>
										<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 text-theme-muted"
										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}
							</div>
						</div>
					</a>
				{/each}
			</div>
		{:else}
			<div class="rounded-xl border border-theme bg-theme-card p-8 text-center">
				<svg
					class="mx-auto mb-4 h-16 w-16 text-theme-muted"
					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>
				<h2 class="mb-2 text-lg font-semibold text-theme">No Upcoming Items</h2>
				<p class="mx-auto max-w-md text-theme-muted">
					{#if activeFilter === 'services'}
						No upcoming services scheduled.
					{:else if activeFilter === 'projects'}
						No upcoming projects scheduled.
					{:else}
						No upcoming services or projects scheduled.
					{/if}
				</p>
			</div>
		{/if}
	</ContentContainer>
</div>
