<script lang="ts">
	import ContentContainer from '$lib/components/layout/ContentContainer.svelte';
	import ReportForm from '$lib/components/admin/reports/ReportForm.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 { fromGlobalId } from '$lib/utils/relay';
	import type { PageData } from './$types';

	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
			goto('/admin/reports', { replaceState: true, noScroll: true });
		}
	});

	let teamProfiles = $derived(data.team?.data?.teamProfiles ?? []);
	let reports = $derived(data.reports ?? []);

	// Create lookup map for team members by UUID (defined early for use in effect)
	let teamMemberLookup = $derived(
		new Map(
			teamProfiles.map((profile) => [
				fromGlobalId(profile.id),
				{ id: profile.id, fullName: profile.fullName, lastName: profile.lastName }
			])
		)
	);

	// Sort reports by date descending, then by team member last name ascending
	let sortedReports = $derived(
		[...reports].sort((a, b) => {
			// First sort by date descending
			const dateCompare = b.date.localeCompare(a.date);
			if (dateCompare !== 0) return dateCompare;

			// Then by team member last name ascending
			const aLastName = teamMemberLookup.get(a.teamMemberId)?.lastName ?? '';
			const bLastName = teamMemberLookup.get(b.teamMemberId)?.lastName ?? '';
			return aLastName.localeCompare(bLastName);
		})
	);

	// Search and filter
	let searchQuery = $state('');
	let selectedTeamMemberId = $state<string>('');

	// Filter reports
	let filteredReports = $derived.by(() => {
		let filtered = sortedReports;

		// Filter by team member (comparing UUIDs)
		if (selectedTeamMemberId) {
			const selectedUuid = fromGlobalId(selectedTeamMemberId);
			filtered = filtered.filter((r) => r.teamMemberId === selectedUuid);
		}

		// Filter by search query (team member name or date)
		if (searchQuery.trim()) {
			const query = searchQuery.toLowerCase();
			filtered = filtered.filter((r) => {
				const teamMember = teamMemberLookup.get(r.teamMemberId);
				const name = teamMember?.fullName?.toLowerCase() ?? '';
				const date = formatReportDate(r.date).toLowerCase();
				return name.includes(query) || date.includes(query);
			});
		}

		return filtered;
	});

	// Get team member name from UUID
	function getTeamMemberName(teamMemberId: string): string {
		return teamMemberLookup.get(teamMemberId)?.fullName ?? 'Unknown';
	}

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

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

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

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

	// Non-admin team members for filter dropdown
	let nonAdminTeamMembers = $derived(teamProfiles.filter((p) => p.role !== 'ADMIN'));
</script>

{#snippet createFormContent()}
	<ReportForm {teamProfiles} onSuccess={handleSuccess} />
{/snippet}

<svelte:head>
	<title>Reports - Admin - Nexus</title>
</svelte:head>

<div class="py-8">
	<ContentContainer>
		<!-- Header -->
		<div class="mb-8">
			<div class="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
				<div class="flex items-start gap-4">
					<a
						href="/admin"
						class="rounded-lg p-1 text-theme-muted hover:bg-black/5 hover:text-theme dark:hover:bg-white/10"
						aria-label="Go back"
					>
						<svg class="h-5 w-5" style="fill: none" stroke="currentColor" viewBox="0 0 24 24">
							<path
								stroke-linecap="round"
								stroke-linejoin="round"
								stroke-width="2"
								d="M15 19l-7-7 7-7"
							/>
						</svg>
					</a>
					<div>
						<h1 class="text-2xl font-bold text-accent2-600 md:text-3xl dark:text-accent2-400">
							Reports
						</h1>
						<p class="mt-2 text-theme-secondary">
							Create and manage monthly labor reports for team members.
						</p>
					</div>
				</div>
				<button
					type="button"
					onclick={showCreateForm}
					class="hidden items-center gap-2 rounded-lg bg-primary-500 px-4 py-2 text-white transition-colors hover:bg-primary-600 sm:inline-flex"
				>
					<svg class="h-5 w-5" style="fill: none" stroke="currentColor" viewBox="0 0 24 24">
						<path
							stroke-linecap="round"
							stroke-linejoin="round"
							stroke-width="2"
							d="M12 4v16m8-8H4"
						/>
					</svg>
					<span>Create Report</span>
				</button>
			</div>
		</div>

		<!-- Search and Filter -->
		<div class="mb-6 flex flex-col gap-4 sm:flex-row">
			<!-- Search -->
			<div class="relative flex-1">
				<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 reports..."
					class="placeholder-theme-muted w-full rounded-lg border border-theme bg-theme-card py-2 pr-4 pl-10 text-theme focus:border-primary-500 focus:ring-1 focus:ring-primary-500"
				/>
			</div>

			<!-- Team Member Filter -->
			<select
				bind:value={selectedTeamMemberId}
				class="rounded-lg border border-theme bg-theme-card px-3 py-2 text-theme focus:border-primary-500 focus:ring-1 focus:ring-primary-500 sm:w-64"
			>
				<option value="">All Team Members</option>
				{#each nonAdminTeamMembers as profile (profile.id)}
					<option value={profile.id}>{profile.fullName}</option>
				{/each}
			</select>
		</div>

		<!-- Reports List -->
		{#if filteredReports.length > 0}
			<div class="space-y-4">
				{#each filteredReports as report (report.id)}
					<a href="/admin/reports/{report.id}" class="block">
						<div class="card-report">
							<div class="flex items-start justify-between gap-4">
								<div class="min-w-0 flex-1 space-y-3">
									<!-- Report Month & Team Member -->
									<div>
										<h3 class="text-lg font-semibold text-accent2-600 dark:text-accent2-400">
											{formatReportDate(report.date)}
										</h3>
										<p class="text-sm text-theme-secondary">
											{getTeamMemberName(report.teamMemberId)}
										</p>
									</div>

									<!-- Labor Breakdown -->
									<div class="grid grid-cols-1 gap-3 sm:grid-cols-3">
										<!-- Services Labor -->
										<div class="rounded-lg bg-secondary-500/10 p-3">
											<p
												class="text-xs font-medium tracking-wide text-secondary-600 uppercase dark:text-secondary-400"
											>
												Services
											</p>
											<p class="mt-1 text-lg font-bold text-secondary-700 dark:text-secondary-300">
												{formatCurrency(report.servicesLaborTotal)}
											</p>
										</div>

										<!-- Projects Labor -->
										<div class="rounded-lg bg-accent-500/10 p-3">
											<p
												class="text-xs font-medium tracking-wide text-accent-600 uppercase dark:text-accent-400"
											>
												Projects
											</p>
											<p class="mt-1 text-lg font-bold text-accent-700 dark:text-accent-300">
												{formatCurrency(report.projectsLaborTotal)}
											</p>
										</div>

										<!-- Total Labor -->
										<div class="rounded-lg bg-accent2-500/10 p-3">
											<p
												class="text-xs font-medium tracking-wide text-accent2-600 uppercase dark:text-accent2-400"
											>
												Total
											</p>
											<p class="mt-1 text-lg font-bold text-accent2-700 dark:text-accent2-300">
												{formatCurrency(report.totalLaborValue)}
											</p>
										</div>
									</div>
								</div>

								<!-- Chevron -->
								<svg
									class="mt-1 h-5 w-5 flex-shrink-0 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>
							</div>
						</div>
					</a>
				{/each}
			</div>
		{:else if searchQuery || selectedTeamMemberId}
			<div class="empty-state">
				<svg
					class="empty-state-icon text-accent2-400"
					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>
				<h2 class="empty-state-title">No Reports Found</h2>
				<p class="empty-state-text">
					No reports match your search criteria. Try adjusting your filters.
				</p>
			</div>
		{:else}
			<div class="empty-state">
				<svg
					class="empty-state-icon text-accent2-400"
					style="fill: none"
					stroke="currentColor"
					viewBox="0 0 24 24"
				>
					<path
						stroke-linecap="round"
						stroke-linejoin="round"
						stroke-width="1.5"
						d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z"
					/>
				</svg>
				<h2 class="empty-state-title">No Reports Yet</h2>
				<p class="empty-state-text">
					Get started by creating your first labor report. Reports track team member earnings from
					completed services and projects.
				</p>
				<button
					type="button"
					onclick={showCreateForm}
					class="mt-4 inline-flex items-center gap-2 rounded-lg bg-primary-500 px-4 py-2 text-white transition-colors hover:bg-primary-600"
				>
					<svg class="h-5 w-5" style="fill: none" stroke="currentColor" viewBox="0 0 24 24">
						<path
							stroke-linecap="round"
							stroke-linejoin="round"
							stroke-width="2"
							d="M12 4v16m8-8H4"
						/>
					</svg>
					<span>Create Report</span>
				</button>
			</div>
		{/if}
	</ContentContainer>
</div>

<!-- Mobile FAB -->
<button
	type="button"
	onclick={showCreateForm}
	class="fixed right-4 bottom-20 z-30 flex h-14 w-14 items-center justify-center rounded-full bg-primary-500 text-white shadow-lg transition-colors hover:bg-primary-600 sm:hidden"
	aria-label="Create Report"
>
	<svg class="h-6 w-6" style="fill: none" stroke="currentColor" viewBox="0 0 24 24">
		<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4" />
	</svg>
</button>
