<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, type AccountAddressInfo, type CustomerInfo } from '$lib/utils/lookup';

	type Project = TeamDashboard$result['teamDashboard']['projects'][number];

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

	// Use pre-built lookups from root layout
	let accountLookup = $derived(data.accountLookup);
	let customerLookup = $derived(data.customerLookup);
	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.projects.scheduled ?? []);
	let inProgress = $derived(data.projects.inProgress ?? []);
	let completed = $derived(data.projects.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 project display info: account name, customer name, and address
	function getProjectDisplayInfo(project: Project): {
		accountInfo: AccountAddressInfo | null;
		customerInfo: CustomerInfo | null;
		address: string | null;
	} {
		// If project has accountAddressId, it's affiliated with an account
		if (project.accountAddressId) {
			const accountInfo = accountLookup.get(project.accountAddressId) ?? null;
			return {
				accountInfo,
				customerInfo: null,
				address: accountInfo ? formatAddress(accountInfo) : null
			};
		}

		// Otherwise, use direct address fields on project and match customer
		const customerInfo = project.customerId
			? (customerLookup.get(project.customerId) ?? null)
			: null;
		const address = formatAddress({
			streetAddress: project.streetAddress,
			city: project.city,
			state: project.state,
			zipCode: project.zipCode
		});

		return { accountInfo: null, customerInfo, address };
	}
</script>

<WorkListLayout
	title="Projects"
	subtitle="Your one-time cleaning assignments. Start a session to log completed tasks, photos, and notes."
	items={currentData}
	{currentStatus}
	currentMonth={data.filters.month}
	{counts}
	emptyTitle="No Projects"
	emptyText="No projects found for this month and status."
	colorScheme="accent"
>
	{#snippet emptyIcon()}
		<svg
			class="empty-state-icon text-accent-400"
			style="fill: none"
			stroke="currentColor"
			viewBox="0 0 24 24"
		>
			<path
				stroke-linecap="round"
				stroke-linejoin="round"
				stroke-width="1.5"
				d="M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-6l-2-2H5a2 2 0 00-2 2z"
			/>
		</svg>
	{/snippet}

	{#snippet item(project: Project)}
		{@const displayInfo = getProjectDisplayInfo(project)}
		{@const teamCount = countNonAdminTeamMembers(project.teamMembers)}
		<a href="/team/projects/{project.id}" class="block">
			<div class="card-project">
				<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(project.date)}
							</span>
							<span
								class="rounded-full px-3 py-1 text-xs font-medium {getStatusClass(project.status)}"
							>
								{project.status.replace('_', ' ')}
							</span>
						</div>
						<!-- Row 2: Account/Customer Name -->
						{#if displayInfo.accountInfo}
							<p class="text-base font-semibold text-primary-500">
								{displayInfo.accountInfo.accountName}
							</p>
						{:else if displayInfo.customerInfo}
							<p class="text-base font-semibold text-primary-500">
								{displayInfo.customerInfo.customerName}
							</p>
						{:else}
							<p class="text-base font-semibold text-theme-muted italic">
								No account/customer linked
							</p>
						{/if}
						<!-- Row 3: Project Name -->
						<p class="text-sm text-theme-secondary">{project.name}</p>
						<!-- Row 4: Address -->
						{#if displayInfo.address}
							<p class="text-sm text-theme-muted">{displayInfo.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 project.notes}
							<p class="line-clamp-2 text-sm text-theme-muted italic">{project.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>
