<script lang="ts">
	import WorkListLayout from '$lib/components/team/WorkListLayout.svelte';
	import { page } from '$app/state';
	import type { PageData } from './$types';
	import type { TeamDashboard$result } from '$houdini';
	import { formatAddress } from '$lib/utils/lookup';

	type Service = TeamDashboard$result['teamDashboard']['services'][number];

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

	// Use pre-built lookups from root layout
	let accountLookup = $derived(data.accountLookup);
	let nonAdminTeamIds = $derived(data.nonAdminTeamIds);

	// Count non-admin team members
	function countNonAdminTeamMembers(teamMembers: { pk: string }[] | null | undefined): number {
		if (!teamMembers) return 0;
		return teamMembers.filter((m) => nonAdminTeamIds.has(m.pk)).length;
	}

	// Get current status from URL, default to 'scheduled'
	let currentStatus = $derived(page.url.searchParams.get('status') || 'scheduled');

	// Extract data from each status - now flat arrays
	let scheduled = $derived(data.services.scheduled ?? []);
	let inProgress = $derived(data.services.inProgress ?? []);
	let completed = $derived(data.services.completed ?? []);

	// Calculate counts for tabs
	let counts = $derived({
		scheduled: scheduled.length,
		inProgress: inProgress.length,
		completed: completed.length
	});

	// Select current data based on status
	let currentData = $derived(
		currentStatus === 'scheduled'
			? scheduled
			: currentStatus === 'in_progress'
				? inProgress
				: completed
	);

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

	// Get status badge class
	function getStatusClass(status: string): string {
		switch (status) {
			case 'SCHEDULED':
				return 'badge-primary';
			case 'IN_PROGRESS':
				return 'badge-accent';
			case 'COMPLETED':
				return 'badge-secondary';
			default:
				return 'bg-gray-100 text-gray-800 dark:bg-gray-800 dark:text-gray-200';
		}
	}

	// Get account info for a service
	function getAccountInfo(accountAddressId: string | null | undefined) {
		if (!accountAddressId) return null;
		return accountLookup.get(accountAddressId) ?? null;
	}
</script>

<WorkListLayout
	title="Services"
	subtitle="Your recurring cleaning assignments. Start a session to log completed tasks, photos, and notes for each visit."
	items={currentData}
	{currentStatus}
	currentMonth={data.filters.month}
	{counts}
	emptyTitle="No Services"
	emptyText="No services found for this month and status."
	colorScheme="secondary"
>
	{#snippet emptyIcon()}
		<svg
			class="empty-state-icon text-secondary-400"
			style="fill: none"
			stroke="currentColor"
			viewBox="0 0 24 24"
		>
			<path
				stroke-linecap="round"
				stroke-linejoin="round"
				stroke-width="1.5"
				d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"
			/>
			<path
				stroke-linecap="round"
				stroke-linejoin="round"
				stroke-width="1.5"
				d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"
			/>
		</svg>
	{/snippet}

	{#snippet item(service: Service)}
		{@const accountInfo = getAccountInfo(service.accountAddressId)}
		{@const address = accountInfo ? formatAddress(accountInfo) : null}
		{@const teamCount = countNonAdminTeamMembers(service.teamMembers)}
		<a href="/team/services/{service.id}" class="block">
			<div class="card-service">
				<div class="flex items-start justify-between gap-4">
					<div class="min-w-0 flex-1 space-y-1">
						<!-- Row 1: Date + Status badges -->
						<div class="flex flex-wrap items-center gap-2">
							<span
								class="rounded-full border border-theme bg-theme-secondary px-3 py-1 text-xs font-medium text-theme"
							>
								{formatDate(service.date)}
							</span>
							<span
								class="rounded-full px-3 py-1 text-xs font-medium {getStatusClass(service.status)}"
							>
								{service.status.replace('_', ' ')}
							</span>
						</div>
						<!-- Row 2: Account Name -->
						{#if accountInfo}
							<p class="text-base font-semibold text-primary-500">{accountInfo.accountName}</p>
						{:else}
							<p class="text-base font-semibold text-theme-muted italic">No account linked</p>
						{/if}
						<!-- Row 3: Address Name -->
						{#if accountInfo}
							<p class="text-sm text-theme-secondary">{accountInfo.addressName}</p>
						{/if}
						<!-- Row 4: Address -->
						{#if address}
							<p class="text-sm text-theme-muted">{address}</p>
						{/if}
						<!-- Row 5: Team Members -->
						<p class="text-sm text-theme-muted">
							{teamCount} team member{teamCount !== 1 ? 's' : ''} assigned
						</p>
						<!-- Row 6: Notes -->
						{#if service.notes}
							<p class="line-clamp-2 text-sm text-theme-muted italic">{service.notes}</p>
						{/if}
					</div>
					<svg
						class="mt-1 h-5 w-5 flex-shrink-0 text-theme-muted"
						style="fill: none"
						viewBox="0 0 24 24"
						stroke="currentColor"
						stroke-width="2"
					>
						<path stroke-linecap="round" stroke-linejoin="round" d="M9 5l7 7-7 7" />
					</svg>
				</div>
			</div>
		</a>
	{/snippet}
</WorkListLayout>
