<script lang="ts">
	import type { PageData } from './$types';
	import { ContentContainer } from '$lib/components/layout';
	import { PageHeader, MonthSelector, StatusTabs, Pagination } from '$lib/components/admin';
	import type { WorkStatus, ServiceTeamMember } from '$lib/graphql/queries/services';

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

	// Local search filter (client-side)
	let searchQuery = $state('');

	let services = $derived(data.services?.items ?? []);

	let filteredServices = $derived(
		services.filter((s) => {
			if (!searchQuery) return true;
			const query = searchQuery.toLowerCase();
			const accountName = s.account?.name?.toLowerCase() ?? '';
			const customerName = s.account?.customer?.name?.toLowerCase() ?? '';
			const addressName = s.accountAddress?.name?.toLowerCase() ?? '';
			const city = s.accountAddress?.city?.toLowerCase() ?? '';
			return (
				accountName.includes(query) ||
				customerName.includes(query) ||
				addressName.includes(query) ||
				city.includes(query)
			);
		})
	);

	function isDispatched(teamMembers: ServiceTeamMember[]): boolean {
		return teamMembers.some((m) => m.teamProfile?.role === 'ADMIN');
	}

	function isAssigned(teamMembers: ServiceTeamMember[]): boolean {
		return teamMembers.some((m) => m.teamProfile?.role && m.teamProfile.role !== 'ADMIN');
	}

	function formatTeamMembers(teamMembers: ServiceTeamMember[]): string {
		const names = teamMembers
			.filter((m) => m.teamProfile?.role && m.teamProfile.role !== 'ADMIN')
			.map((m) => m.teamProfile?.fullName ?? '')
			.filter((name) => name !== '');

		if (names.length === 0) return '';
		if (names.length <= 2) return names.join(', ');
		return `${names.slice(0, 2).join(', ')} +${names.length - 2} other${names.length - 2 > 1 ? 's' : ''}`;
	}

	function getStatusBadgeClass(status: WorkStatus): string {
		switch (status) {
			case 'SCHEDULED':
				return 'bg-accent2-100 text-accent2-800 dark:bg-accent2-900/30 dark:text-accent2-400';
			case 'IN_PROGRESS':
				return 'bg-accent-100 text-accent-800 dark:bg-accent-900/30 dark:text-accent-400';
			case 'COMPLETED':
				return 'bg-primary-100 text-primary-800 dark:bg-primary-900/30 dark:text-primary-400';
			case 'CANCELLED':
				return 'bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400';
			default:
				return 'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-300';
		}
	}

	function formatStatusLabel(status: WorkStatus): string {
		switch (status) {
			case 'IN_PROGRESS':
				return 'In Progress';
			default:
				return status.charAt(0) + status.slice(1).toLowerCase();
		}
	}

	function formatDate(dateStr: string): string {
		const date = new Date(dateStr + 'T00:00:00');
		return date.toLocaleDateString('en-US', {
			weekday: 'short',
			month: 'short',
			day: 'numeric'
		});
	}

	function formatAddress(
		address: { streetAddress: string; city: string; state: string } | null
	): string {
		if (!address) return '';
		return `${address.city}, ${address.state}`;
	}
</script>

<svelte:head>
	<title>My Services - Nexus</title>
</svelte:head>

<div class="py-8">
	<ContentContainer>
		<PageHeader
			title="My Services"
			subtitle="{data.services?.totalCount ?? 0} service{(data.services?.totalCount ?? 0) !== 1
				? 's'
				: ''} for {data.month}"
			backHref="/team"
			colorScheme="secondary"
		/>

		<!-- Month Selector and Status Tabs -->
		<div class="mb-6 flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
			<MonthSelector month={data.month} />
			<StatusTabs counts={data.statusCounts} currentStatus={data.status} />
		</div>

		<!-- Search -->
		<div class="mb-6">
			<div class="relative">
				<svg
					class="absolute top-1/2 left-3 h-5 w-5 -translate-y-1/2 text-theme-muted"
					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 by account, customer, or location..."
					class="placeholder-theme-muted w-full rounded-lg border border-theme bg-theme py-2 pr-4 pl-10 text-theme focus:border-primary-500 focus:ring-1 focus:ring-primary-500 focus:outline-none"
				/>
			</div>
		</div>

		<!-- Service List -->
		{#if filteredServices.length > 0}
			<div class="mb-6 grid grid-cols-1 gap-4 md:grid-cols-2">
				{#each filteredServices as service (service.id)}
					<a href="/team/services/{service.id}" class="block card-service">
						<!-- Account Name -->
						<h2 class="truncate text-lg font-semibold text-theme">
							{service.account?.name ?? 'Unknown Account'}
						</h2>

						<!-- Customer if different from account -->
						{#if service.account?.customer}
							<p class="truncate text-sm text-theme-secondary">
								{service.account.customer.name}
							</p>
						{/if}

						<!-- Location -->
						{#if service.accountAddress}
							<p class="mt-1 truncate text-sm text-theme-muted">
								{#if service.accountAddress.name}
									{service.accountAddress.name} -
								{/if}
								{formatAddress(service.accountAddress)}
							</p>
						{/if}

						<!-- Date and Team -->
						<div class="mt-3 flex items-center justify-between gap-2 text-sm">
							<span class="shrink-0 text-theme-secondary">{formatDate(service.date)}</span>
							{#if formatTeamMembers(service.teamMembers)}
								<span class="truncate text-theme-muted">
									{formatTeamMembers(service.teamMembers)}
								</span>
							{/if}
						</div>

						<!-- Badges -->
						<div class="mt-2 flex flex-wrap gap-1">
							<span
								class="inline-flex rounded-full px-2 py-0.5 text-xs font-semibold {getStatusBadgeClass(
									service.status
								)}"
							>
								{formatStatusLabel(service.status)}
							</span>
							{#if isDispatched(service.teamMembers)}
								<span
									class="inline-flex rounded-full bg-purple-100 px-2 py-0.5 text-xs font-semibold text-purple-800 dark:bg-purple-900/30 dark:text-purple-400"
								>
									Dispatched
								</span>
							{/if}
							{#if isAssigned(service.teamMembers)}
								<span
									class="inline-flex rounded-full bg-blue-100 px-2 py-0.5 text-xs font-semibold text-blue-800 dark:bg-blue-900/30 dark:text-blue-400"
								>
									Assigned
								</span>
							{/if}
						</div>
					</a>
				{/each}
			</div>

			<!-- Pagination -->
			<Pagination
				currentPage={data.page}
				totalCount={data.services?.totalCount ?? 0}
				limit={data.limit}
				hasNextPage={data.services?.hasNextPage ?? false}
			/>
		{:else if searchQuery}
			<!-- No results with search -->
			<div class="rounded-lg border border-theme bg-theme-secondary py-12 text-center">
				<svg
					class="mx-auto h-12 w-12 text-theme-muted"
					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="mt-4 text-lg font-medium text-theme">No services found</h3>
				<p class="mt-2 text-theme-secondary">No services match your search.</p>
				<button
					type="button"
					onclick={() => (searchQuery = '')}
					class="mt-4 text-primary-500 hover:text-primary-600"
				>
					Clear search
				</button>
			</div>
		{:else if (data.services?.totalCount ?? 0) === 0}
			<!-- Empty state for month/status -->
			<div class="rounded-lg border border-theme bg-theme-secondary py-12 text-center">
				<svg
					class="mx-auto h-12 w-12 text-theme-muted"
					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>
				<h3 class="mt-4 text-lg font-medium text-theme">No services</h3>
				<p class="mt-2 text-theme-secondary">
					{#if data.status}
						No {formatStatusLabel(data.status).toLowerCase()} services for this month.
					{:else}
						No services assigned to you for this month.
					{/if}
				</p>
			</div>
		{/if}
	</ContentContainer>
</div>
