<script lang="ts">
	import AdminListLayout from '$lib/components/admin/AdminListLayout.svelte';
	import ProjectForm from '$lib/components/admin/projects/ProjectForm.svelte';
	import { offCanvas } from '$lib/stores/offCanvas.svelte';
	import { goto } from '$app/navigation';
	import { invalidateDashboard } from '$lib/utils/invalidate';
	import { page } from '$app/state';
	import type { PageData } from './$types';
	import type { AdminProjects$result } from '$houdini';
	import { formatAddress } from '$lib/utils/lookup';
	import { fromGlobalId } from '$lib/utils/relay';

	type Project = AdminProjects$result['projects'][number];

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

	// Auto-open create form if action=create is in URL
	$effect(() => {
		if (page.url.searchParams.get('action') === 'create') {
			showCreateForm();
			// Remove the action param from URL without navigation
			const newUrl = new URL(page.url);
			newUrl.searchParams.delete('action');
			goto(newUrl.pathname + newUrl.search, { replaceState: true, noScroll: true });
		}
	});

	// Use pre-built lookups from root layout
	let accountLookup = $derived(data.accountLookup);
	let customerLookup = $derived(data.customerLookup);
	let customers = $derived(data.customers?.data?.customers ?? []);
	let accounts = $derived(data.accounts?.data?.accounts ?? []);
	let teamProfiles = $derived(data.team?.data?.teamProfiles ?? []);
	let nonAdminTeamIds = $derived(data.nonAdminTeamIds);

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

	// Extract data from each status
	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
	);

	// Search
	let searchQuery = $state('');
	let filteredProjects = $derived(() => {
		if (!searchQuery.trim()) return currentData;
		const query = searchQuery.toLowerCase();
		return currentData.filter((project) => {
			// Search project name
			if (project.name.toLowerCase().includes(query)) return true;
			// Search account name
			if (project.accountAddressId) {
				const accountInfo = accountLookup.get(project.accountAddressId);
				if (accountInfo?.accountName.toLowerCase().includes(query)) return true;
			}
			// Search customer name
			if (project.customerId) {
				const customerInfo = customerLookup.get(project.customerId);
				if (customerInfo?.customerName.toLowerCase().includes(query)) return true;
			}
			return false;
		});
	});

	// 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 admin profile UUID for dispatched check
	let adminProfileUuid = $derived(() => {
		const adminProfile = teamProfiles.find((p) => p.role === 'ADMIN');
		return adminProfile ? fromGlobalId(adminProfile.id) : null;
	});

	// Check if project is dispatched (admin is in team members)
	function isDispatched(teamMembers: { pk: string }[] | null | undefined): boolean {
		const adminUuid = adminProfileUuid();
		if (!adminUuid || !teamMembers) return false;
		return teamMembers.some((m) => m.pk === adminUuid);
	}

	// Check if project has non-admin team members assigned
	function hasNonAdminTeamMembers(teamMembers: { pk: string }[] | null | undefined): boolean {
		return countNonAdminTeamMembers(teamMembers) > 0;
	}

	// 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
	function getProjectDisplayInfo(project: Project): {
		accountName: string | null;
		customerName: string | null;
		address: string | null;
	} {
		if (project.accountAddressId) {
			const accountInfo = accountLookup.get(project.accountAddressId);
			return {
				accountName: accountInfo?.accountName ?? null,
				customerName: null,
				address: accountInfo ? formatAddress(accountInfo) : null
			};
		}

		const customerInfo = project.customerId ? customerLookup.get(project.customerId) : null;
		const address = formatAddress({
			streetAddress: project.streetAddress,
			city: project.city,
			state: project.state,
			zipCode: project.zipCode
		});

		return {
			accountName: null,
			customerName: customerInfo?.customerName ?? null,
			address
		};
	}

	// Format currency
	function formatCurrency(amount: number | string | null | undefined): string {
		if (amount == null) return '$0';
		const num = typeof amount === 'string' ? parseFloat(amount) : amount;
		return new Intl.NumberFormat('en-US', {
			style: 'currency',
			currency: 'USD',
			minimumFractionDigits: 0,
			maximumFractionDigits: 0
		}).format(num);
	}

	function showCreateForm() {
		offCanvas.showRight({
			title: 'Create Project',
			content: createFormContent
		});
	}

	async function handleSuccess() {
		await invalidateDashboard();
	}

	// Determine empty text based on search
	let emptyText = $derived(
		searchQuery
			? `No projects match "${searchQuery}". Try a different search term.`
			: 'No projects found for this month and status.'
	);
</script>

{#snippet createFormContent()}
	<ProjectForm {customers} {accounts} {teamProfiles} onSuccess={handleSuccess} />
{/snippet}

{#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 projectItem(project: Project)}
	{@const displayInfo = getProjectDisplayInfo(project)}
	{@const teamCount = countNonAdminTeamMembers(project.teamMembers)}
	<a href="/admin/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>
						{#if isDispatched(project.teamMembers)}
							<span
								class="rounded-full bg-emerald-100 px-3 py-1 text-xs font-medium text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400"
							>
								Dispatched
							</span>
						{/if}
						{#if hasNonAdminTeamMembers(project.teamMembers)}
							<span
								class="rounded-full bg-blue-100 px-3 py-1 text-xs font-medium text-blue-700 dark:bg-blue-900/30 dark:text-blue-400"
							>
								Assigned
							</span>
						{/if}
						{#if project.waveServiceId}
							<span class="badge-primary">Linked</span>
						{/if}
					</div>
					<!-- Row 2: Account/Customer Name -->
					{#if displayInfo.accountName}
						<p class="text-base font-semibold text-primary-500">
							{displayInfo.accountName}
						</p>
					{:else if displayInfo.customerName}
						<p class="text-base font-semibold text-primary-500">
							{displayInfo.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: Amount + Team -->
					<div class="flex flex-wrap items-center gap-4 text-sm text-theme-muted">
						<span>{formatCurrency(project.amount)}</span>
						<span>{teamCount} team member{teamCount !== 1 ? 's' : ''}</span>
					</div>
					<!-- 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 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}

<AdminListLayout
	title="Projects"
	subtitle="Manage one-time cleaning projects. Create, track progress, and view completed work."
	items={filteredProjects()}
	{currentStatus}
	currentMonth={data.currentMonth}
	{counts}
	emptyTitle="No Projects"
	{emptyText}
	colorScheme="accent"
	{searchQuery}
	onSearchChange={(q) => (searchQuery = q)}
	searchPlaceholder="Search projects..."
	createButtonText="New Project"
	onCreateClick={showCreateForm}
	{emptyIcon}
	item={projectItem}
/>
