<script lang="ts">
	import ContentContainer from '$lib/components/layout/ContentContainer.svelte';
	import TeamPageHeader from '$lib/components/team/TeamPageHeader.svelte';
	import type { PageData } from './$types';

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

	let report = $derived(data.report);
	let accountLookup = $derived(data.accountLookup);
	let customerLookup = $derived(data.customerLookup);

	// Create lookup maps for labor breakdown by service/project ID
	let serviceLaborMap = $derived(
		new Map(
			(report.laborBreakdown?.services ?? []).map((s) => [
				s.serviceId,
				{
					totalLaborRate: s.totalLaborRate as string | number,
					teamMemberCount: s.teamMemberCount,
					laborShare: s.laborShare as string | number
				}
			])
		)
	);

	let projectLaborMap = $derived(
		new Map(
			(report.laborBreakdown?.projects ?? []).map((p) => [
				p.projectId,
				{
					totalLaborAmount: p.totalLaborAmount as string | number,
					teamMemberCount: p.teamMemberCount,
					laborShare: p.laborShare as string | number
				}
			])
		)
	);

	// Format date for display (Month Year)
	function formatReportDate(dateStr: string): string {
		const [year, month] = dateStr.split('-').map(Number);
		const date = new Date(year, month - 1, 1);
		return date.toLocaleDateString('en-US', {
			month: 'long',
			year: 'numeric'
		});
	}

	// Format item date (short)
	function formatItemDate(dateStr: string): string {
		return new Date(dateStr + 'T00:00:00').toLocaleDateString('en-US', {
			month: 'short',
			day: 'numeric'
		});
	}

	// Get service display name: "Date, Account Name"
	function getServiceDisplayName(service: {
		date: string;
		accountAddressId: string | null;
	}): string {
		const dateStr = formatItemDate(service.date);
		const addressInfo = service.accountAddressId
			? accountLookup.get(service.accountAddressId)
			: null;
		const accountName = addressInfo?.accountName ?? 'Unknown Account';
		return `${dateStr}, ${accountName}`;
	}

	// Get project display name: "Date, Account/Customer - Project Name"
	function getProjectDisplayName(project: {
		date: string;
		name: string;
		accountAddressId: string | null;
		customerId: string | null;
	}): string {
		const dateStr = formatItemDate(project.date);

		let entityName = 'Unknown';
		if (project.accountAddressId) {
			const addressInfo = accountLookup.get(project.accountAddressId);
			if (addressInfo) {
				entityName = addressInfo.accountName;
			}
		} else if (project.customerId) {
			const customerInfo = customerLookup.get(project.customerId);
			if (customerInfo) {
				entityName = customerInfo.customerName;
			}
		}

		return `${dateStr}, ${entityName} - ${project.name}`;
	}

	// 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);
	}

	let reportTitle = $derived(formatReportDate(report.date));
</script>

<svelte:head>
	<title>{reportTitle} Report - Nexus</title>
</svelte:head>

<div class="py-8">
	<ContentContainer>
		<TeamPageHeader
			title={reportTitle}
			subtitle="Monthly labor summary and payment breakdown."
			colorScheme="accent2"
			backHref="/team/reports"
		/>

		<!-- Labor Summary Card -->
		<div class="mb-6 card-padded">
			<h3 class="mb-4 text-sm font-medium text-theme-muted">Labor Summary</h3>

			<div class="space-y-4">
				<!-- Services Labor -->
				<div class="flex items-center justify-between border-b border-theme py-3">
					<div class="flex items-center gap-3">
						<div class="flex h-10 w-10 items-center justify-center rounded-lg bg-secondary-500/20">
							<svg
								class="h-5 w-5 text-secondary-600 dark:text-secondary-400"
								style="fill: none"
								stroke="currentColor"
								viewBox="0 0 24 24"
							>
								<path
									stroke-linecap="round"
									stroke-linejoin="round"
									stroke-width="2"
									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="2"
									d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"
								/>
							</svg>
						</div>
						<div>
							<p class="font-medium text-theme">Services</p>
							<p class="text-sm text-theme-muted">
								{report.services.length} service{report.services.length !== 1 ? 's' : ''}
							</p>
						</div>
					</div>
					<p class="text-lg font-bold text-secondary-600 dark:text-secondary-400">
						{formatCurrency(report.servicesLaborTotal)}
					</p>
				</div>

				<!-- Projects Labor -->
				<div class="flex items-center justify-between border-b border-theme py-3">
					<div class="flex items-center gap-3">
						<div class="flex h-10 w-10 items-center justify-center rounded-lg bg-accent-500/20">
							<svg
								class="h-5 w-5 text-accent-600 dark:text-accent-400"
								style="fill: none"
								stroke="currentColor"
								viewBox="0 0 24 24"
							>
								<path
									stroke-linecap="round"
									stroke-linejoin="round"
									stroke-width="2"
									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>
						</div>
						<div>
							<p class="font-medium text-theme">Projects</p>
							<p class="text-sm text-theme-muted">
								{report.projects.length} project{report.projects.length !== 1 ? 's' : ''}
							</p>
						</div>
					</div>
					<p class="text-lg font-bold text-accent-600 dark:text-accent-400">
						{formatCurrency(report.projectsLaborTotal)}
					</p>
				</div>

				<!-- Total -->
				<div class="flex items-center justify-between py-3">
					<div class="flex items-center gap-3">
						<div class="flex h-10 w-10 items-center justify-center rounded-lg bg-accent2-500/20">
							<svg
								class="h-5 w-5 text-accent2-600 dark:text-accent2-400"
								style="fill: none"
								stroke="currentColor"
								viewBox="0 0 24 24"
							>
								<path
									stroke-linecap="round"
									stroke-linejoin="round"
									stroke-width="2"
									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>
						</div>
						<div>
							<p class="font-medium text-theme">Total Labor</p>
							<p class="text-sm text-theme-muted">Combined earnings for the month</p>
						</div>
					</div>
					<p class="text-xl font-bold text-accent2-600 dark:text-accent2-400">
						{formatCurrency(report.totalLaborValue)}
					</p>
				</div>
			</div>
		</div>

		<!-- Services Section -->
		<div class="mb-6 card-padded">
			<h3 class="mb-4 text-sm font-medium text-theme-muted">Services</h3>

			{#if report.services.length === 0}
				<p class="text-sm text-theme-muted italic">No services in this report.</p>
			{:else}
				<div class="space-y-2">
					{#each report.services as service (service.id)}
						{@const labor = serviceLaborMap.get(service.id)}
						<div class="rounded-lg border border-theme bg-theme-secondary p-3">
							<div class="flex items-start justify-between gap-2">
								<div class="min-w-0 flex-1">
									<p class="text-sm font-medium text-theme">{getServiceDisplayName(service)}</p>
									{#if labor}
										<div
											class="mt-1 flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-theme-muted"
										>
											<span>Total: {formatCurrency(labor.totalLaborRate)}</span>
											<span>Team: {labor.teamMemberCount}</span>
											<span class="font-semibold text-secondary-600 dark:text-secondary-400">
												Share: {formatCurrency(labor.laborShare)}
											</span>
										</div>
									{/if}
								</div>
							</div>
						</div>
					{/each}
				</div>
			{/if}
		</div>

		<!-- Projects Section -->
		<div class="mb-6 card-padded">
			<h3 class="mb-4 text-sm font-medium text-theme-muted">Projects</h3>

			{#if report.projects.length === 0}
				<p class="text-sm text-theme-muted italic">No projects in this report.</p>
			{:else}
				<div class="space-y-2">
					{#each report.projects as project (project.id)}
						{@const labor = projectLaborMap.get(project.id)}
						<div class="rounded-lg border border-theme bg-theme-secondary p-3">
							<div class="flex items-start justify-between gap-2">
								<div class="min-w-0 flex-1">
									<p class="text-sm font-medium text-theme">{getProjectDisplayName(project)}</p>
									{#if labor}
										<div
											class="mt-1 flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-theme-muted"
										>
											<span>Total: {formatCurrency(labor.totalLaborAmount)}</span>
											<span>Team: {labor.teamMemberCount}</span>
											<span class="font-semibold text-accent-600 dark:text-accent-400">
												Share: {formatCurrency(labor.laborShare)}
											</span>
										</div>
									{/if}
								</div>
							</div>
						</div>
					{/each}
				</div>
			{/if}
		</div>

		<!-- Labor Breakdown Details -->
		{#if report.laborBreakdown && (report.laborBreakdown.services.length > 0 || report.laborBreakdown.projects.length > 0)}
			<div class="mb-6 card-padded">
				<h3 class="mb-4 text-sm font-medium text-theme-muted">Labor Breakdown</h3>

				<!-- Totals Summary -->
				<div class="rounded-lg bg-accent2-500/10 p-4">
					<div class="space-y-2">
						<div class="flex items-center justify-between text-sm">
							<span class="text-theme-secondary">Services Total:</span>
							<span class="font-semibold text-theme"
								>{formatCurrency(report.laborBreakdown.servicesTotal)}</span
							>
						</div>
						<div class="flex items-center justify-between text-sm">
							<span class="text-theme-secondary">Projects Total:</span>
							<span class="font-semibold text-theme"
								>{formatCurrency(report.laborBreakdown.projectsTotal)}</span
							>
						</div>
						<div class="flex items-center justify-between border-t border-accent2-500/20 pt-2">
							<span class="font-semibold text-accent2-600 dark:text-accent2-400">Grand Total:</span>
							<span class="text-lg font-bold text-accent2-600 dark:text-accent2-400"
								>{formatCurrency(report.laborBreakdown.grandTotal)}</span
							>
						</div>
					</div>
				</div>
			</div>
		{/if}

		<!-- Back Button -->
		<a href="/team/reports" class="btn-ghost block w-full text-center"> Back to Reports </a>
	</ContentContainer>
</div>
