<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?: {
			completed?: Service[];
		};
		projects?: {
			completed?: Project[];
		};
		customerAccountLookup?: Record<string, CustomerAccountInfo>;
	};

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

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

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

	// Combine and sort items
	type HistoryItem =
		| {
				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: HistoryItem[] = [];

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

		completedProjects.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;
	});

	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<HistoryItem, { 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 ?? ''}`;
	}

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

	// Sort by date descending, then alphabetically by name
	let sortedItems = $derived(
		[...allItems].sort((a, b) => {
			const dateCompare = b.date.localeCompare(a.date); // descending
			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) => {
			// Filter by type
			if (activeFilter === 'services' && item.type !== 'service') return false;
			if (activeFilter === 'projects' && item.type !== 'project') return false;

			// Filter by search
			if (searchQuery) {
				const query = searchQuery.toLowerCase();
				if (item.type === 'service') {
					const accountName = getAccountName(item.accountId, item.accountAddressId).toLowerCase();
					return accountName.includes(query);
				} else {
					return (
						item.name.toLowerCase().includes(query) ||
						item.streetAddress?.toLowerCase().includes(query) ||
						item.city?.toLowerCase().includes(query)
					);
				}
			}

			return true;
		})
	);

	function getItemHref(item: HistoryItem): string {
		if (item.type === 'service') {
			return `/customer/history/service/${item.id}`;
		}
		return `/customer/history/project/${item.id}`;
	}

	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: HistoryItem): boolean {
		if (!navigating.to) return false;
		const href = getItemHref(item);
		return navigating.to.url.pathname === href;
	}
</script>

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

<div class="py-8">
	<ContentContainer>
		<CustomerPageHeader
			title="History"
			subtitle="View completed services and projects."
			colorScheme="accent"
		/>

		<!-- Search -->
		<div class="mb-4">
			<div class="relative">
				<svg
					class="absolute top-1/2 left-3 h-5 w-5 -translate-y-1/2 text-theme-muted"
					style="fill: none"
					stroke="currentColor"
					viewBox="0 0 24 24"
				>
					<path
						stroke-linecap="round"
						stroke-linejoin="round"
						stroke-width="2"
						d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"
					/>
				</svg>
				<input
					type="text"
					bind:value={searchQuery}
					placeholder="Search history..."
					class="placeholder-theme-muted w-full rounded-lg border border-theme bg-theme-card py-2.5 pr-4 pl-10 text-theme focus:border-accent-500 focus:ring-1 focus:ring-accent-500 focus:outline-none"
				/>
			</div>
		</div>

		<!-- 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-accent-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>

		<!-- History 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 bg-success-100 px-2 py-1 text-xs text-success-700 dark:bg-success-900/30 dark:text-success-400"
								>
									Completed
								</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 if searchQuery}
			<div class="rounded-xl border border-theme bg-theme-card p-8 text-center">
				<svg
					class="mx-auto mb-4 h-12 w-12 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="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"
					/>
				</svg>
				<h3 class="mb-2 text-lg font-semibold text-theme">No Results</h3>
				<p class="text-theme-muted">No items match your search.</p>
			</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="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"
					/>
				</svg>
				<h2 class="mb-2 text-lg font-semibold text-theme">No History</h2>
				<p class="mx-auto max-w-md text-theme-muted">
					{#if activeFilter === 'services'}
						No completed services yet.
					{:else if activeFilter === 'projects'}
						No completed projects yet.
					{:else}
						No completed services or projects yet.
					{/if}
				</p>
			</div>
		{/if}
	</ContentContainer>
</div>
