<script lang="ts">
	import type { PageData } from './$types';
	import { ContentContainer } from '$lib/components/layout';
	import { PageHeader } from '$lib/components/admin';
	import type { ReportStatus } from '$lib/graphql/queries/reports';

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

	let report = $derived(data.report);

	function formatCurrency(amount: number): string {
		return new Intl.NumberFormat('en-US', {
			style: 'currency',
			currency: 'USD',
			minimumFractionDigits: 2
		}).format(amount);
	}

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

	function formatDateRange(startDate: string, endDate: string): string {
		return `${formatDate(startDate)} - ${formatDate(endDate)}`;
	}

	function getStatusBadgeClass(status: ReportStatus): string {
		switch (status) {
			case 'DRAFT':
				return 'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-300';
			case 'FINALIZED':
				return 'bg-accent-100 text-accent-800 dark:bg-accent-900/30 dark:text-accent-400';
			case 'PAID':
				return 'bg-success-100 text-success-800 dark:bg-success-900/30 dark:text-success-400';
			default:
				return 'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-300';
		}
	}

	function getLocationDisplay(service: (typeof report.services)[number]['service']): string {
		if (!service) return 'Unknown';
		const parts: string[] = [];
		if (service.account?.name) parts.push(service.account.name);
		if (service.accountAddress?.city) parts.push(service.accountAddress.city);
		return parts.join(', ') || 'Unknown location';
	}
</script>

<svelte:head>
	<title>Report - {formatDateRange(report.startDate, report.endDate)} - Nexus</title>
</svelte:head>

<div class="py-8">
	<ContentContainer>
		<PageHeader
			title={formatDateRange(report.startDate, report.endDate)}
			subtitle={report.teamProfile?.fullName ?? undefined}
			backHref="/team/reports"
			colorScheme="accent2"
		>
			<span
				class="inline-flex rounded-full px-2 py-0.5 text-xs font-semibold {getStatusBadgeClass(
					report.status
				)}"
			>
				{report.status}
			</span>
		</PageHeader>

		<div class="space-y-6">
			<!-- Summary Section -->
			<section
				class="overflow-hidden rounded-xl border border-accent2-500/20 bg-theme-card shadow-theme-md"
			>
				<div class="section-header-accent2 px-6 py-4">
					<h2 class="text-lg font-semibold text-theme">Summary</h2>
				</div>
				<div class="grid grid-cols-2 gap-4 p-6 sm:grid-cols-4">
					<div class="text-center">
						<p class="text-2xl font-bold text-theme">{report.serviceCount}</p>
						<p class="text-sm text-theme-secondary">
							Service{report.serviceCount !== 1 ? 's' : ''}
						</p>
					</div>
					<div class="text-center">
						<p class="text-2xl font-bold text-theme">{report.projectCount}</p>
						<p class="text-sm text-theme-secondary">
							Project{report.projectCount !== 1 ? 's' : ''}
						</p>
					</div>
					<div class="text-center">
						<p class="text-2xl font-bold text-secondary-600 dark:text-secondary-400">
							{formatCurrency(report.servicesTotal)}
						</p>
						<p class="text-sm text-theme-secondary">Services Total</p>
					</div>
					<div class="text-center">
						<p class="text-2xl font-bold text-accent-600 dark:text-accent-400">
							{formatCurrency(report.projectsTotal)}
						</p>
						<p class="text-sm text-theme-secondary">Projects Total</p>
					</div>
				</div>
				<div class="border-t border-theme bg-theme-secondary px-6 py-4">
					<div class="flex items-center justify-between">
						<span class="font-medium text-theme">Total Labor</span>
						<span class="text-2xl font-bold text-accent2-600 dark:text-accent2-400">
							{formatCurrency(report.totalLabor)}
						</span>
					</div>
				</div>
			</section>

			<!-- Services Section -->
			{#if report.services.length > 0}
				<section
					class="overflow-hidden rounded-xl border border-secondary-500/20 bg-theme-card shadow-theme-md"
				>
					<div class="section-header-secondary px-6 py-4">
						<h2 class="text-lg font-semibold text-theme">
							Services ({report.serviceCount})
						</h2>
					</div>
					<div class="divide-theme divide-y">
						{#each report.services as entry (entry.id)}
							<div class="flex items-center justify-between p-4">
								<div class="min-w-0 flex-1">
									<p class="font-medium text-theme">
										{entry.service?.account?.customer?.name ?? 'Unknown Customer'}
									</p>
									<p class="text-sm text-theme-secondary">
										{getLocationDisplay(entry.service)}
									</p>
									<p class="text-xs text-theme-muted">
										{entry.service ? formatDate(entry.service.date) : 'Unknown date'}
									</p>
								</div>
								<div class="text-right">
									<p class="font-semibold text-secondary-600 dark:text-secondary-400">
										{formatCurrency(entry.laborShare)}
									</p>
								</div>
							</div>
						{/each}
					</div>
				</section>
			{/if}

			<!-- Projects Section -->
			{#if report.projects.length > 0}
				<section
					class="overflow-hidden rounded-xl border border-accent-500/20 bg-theme-card shadow-theme-md"
				>
					<div class="section-header-accent px-6 py-4">
						<h2 class="text-lg font-semibold text-theme">
							Projects ({report.projectCount})
						</h2>
					</div>
					<div class="divide-theme divide-y">
						{#each report.projects as entry (entry.id)}
							<div class="flex items-center justify-between p-4">
								<div class="min-w-0 flex-1">
									<p class="font-medium text-theme">
										{entry.project?.name ?? 'Unknown Project'}
									</p>
									<p class="text-sm text-theme-secondary">
										{entry.project?.customer?.name ?? 'Unknown Customer'}
									</p>
									{#if entry.project?.formattedAddress}
										<p class="text-xs text-theme-muted">{entry.project.formattedAddress}</p>
									{/if}
									<p class="text-xs text-theme-muted">
										{entry.project ? formatDate(entry.project.date) : 'Unknown date'}
									</p>
								</div>
								<div class="text-right">
									<p class="font-semibold text-accent-600 dark:text-accent-400">
										{formatCurrency(entry.laborShare)}
									</p>
								</div>
							</div>
						{/each}
					</div>
				</section>
			{/if}

			<!-- Empty state if no entries -->
			{#if report.services.length === 0 && report.projects.length === 0}
				<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="M9 17v-2m3 2v-4m3 4v-6m2 10H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"
						/>
					</svg>
					<h3 class="mt-4 text-lg font-medium text-theme">No entries in this report</h3>
					<p class="mt-2 text-theme-secondary">
						This report doesn't have any services or projects yet.
					</p>
				</div>
			{/if}
		</div>
	</ContentContainer>
</div>
