<script lang="ts">
	import ContentContainer from '$lib/components/layout/ContentContainer.svelte';
	import AdminPageHeader from '$lib/components/admin/AdminPageHeader.svelte';
	import DeleteConfirmModal from '$lib/components/admin/DeleteConfirmModal.svelte';
	import AddServicesModal from '$lib/components/admin/reports/AddServicesModal.svelte';
	import AddProjectsModal from '$lib/components/admin/reports/AddProjectsModal.svelte';
	import { DeleteReportStore, UpdateReportStore } from '$houdini';
	import { goto, invalidateAll } from '$app/navigation';
	import { fromGlobalId } from '$lib/utils/relay';
	import type { PageData } from './$types';

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

	let report = $derived(data.report);
	let teamProfiles = $derived(data.team?.data?.teamProfiles ?? []);
	let accountLookup = $derived(data.accountLookup);
	let customerLookup = $derived(data.customerLookup);

	// Get team member name from UUID
	let teamMemberName = $derived(() => {
		const profile = teamProfiles.find((p) => {
			return fromGlobalId(p.id) === report.teamMemberId;
		});
		return profile?.fullName ?? 'Unknown Team Member';
	});

	let showDeleteModal = $state(false);
	let showAddServicesModal = $state(false);
	let showAddProjectsModal = $state(false);
	let isDeleting = $state(false);

	const deleteStore = new DeleteReportStore();
	const updateStore = new UpdateReportStore();

	// 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 (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 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 accountInfo = service.accountAddressId
			? accountLookup.get(service.accountAddressId)
			: null;
		const accountName = accountInfo?.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 accountInfo = accountLookup.get(project.accountAddressId);
			if (accountInfo) {
				entityName = accountInfo.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));

	// Remove a service from the report
	async function removeService(serviceId: string) {
		const currentServiceIds = report.services.map((s) => s.id);
		const newServiceIds = currentServiceIds.filter((id) => id !== serviceId);

		try {
			await updateStore.mutate({
				input: {
					id: report.id,
					serviceIds: newServiceIds.length > 0 ? newServiceIds : null
				}
			});
			await invalidateAll();
		} catch (err) {
			console.error('Failed to remove service:', err);
		}
	}

	// Remove a project from the report
	async function removeProject(projectId: string) {
		const currentProjectIds = report.projects.map((p) => p.id);
		const newProjectIds = currentProjectIds.filter((id) => id !== projectId);

		try {
			await updateStore.mutate({
				input: {
					id: report.id,
					projectIds: newProjectIds.length > 0 ? newProjectIds : null
				}
			});
			await invalidateAll();
		} catch (err) {
			console.error('Failed to remove project:', err);
		}
	}

	async function handleDelete() {
		isDeleting = true;
		try {
			await deleteStore.mutate({ id: report.id });
			await goto('/admin/reports', { invalidateAll: true });
		} catch (err) {
			console.error('Failed to delete report:', err);
			alert('Failed to delete report. Please try again.');
		} finally {
			isDeleting = false;
			showDeleteModal = false;
		}
	}

	async function handleServicesUpdated() {
		await invalidateAll();
	}

	async function handleProjectsUpdated() {
		await invalidateAll();
	}
</script>

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

<div class="py-8">
	<ContentContainer>
		<AdminPageHeader
			title={reportTitle}
			subtitle={teamMemberName()}
			colorScheme="accent2"
			backHref="/admin/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">
			<div class="mb-4 flex items-center justify-between">
				<h3 class="text-sm font-medium text-theme-muted">Services</h3>
				<button
					onclick={() => (showAddServicesModal = true)}
					class="flex items-center gap-1.5 rounded-lg bg-secondary-500/10 px-3 py-1.5 text-sm font-medium text-secondary-600 transition-colors hover:bg-secondary-500/20 dark:text-secondary-400"
				>
					<svg class="h-4 w-4" 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>
					Add Services
				</button>
			</div>

			{#if report.services.length === 0}
				<p class="text-sm text-theme-muted italic">No services added to 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>
								<button
									onclick={() => removeService(service.id)}
									class="rounded p-1 text-theme-muted transition-colors hover:bg-error-500/10 hover:text-error-600 dark:hover:text-error-400"
									title="Remove service"
								>
									<svg class="h-4 w-4" style="fill: none" stroke="currentColor" viewBox="0 0 24 24">
										<path
											stroke-linecap="round"
											stroke-linejoin="round"
											stroke-width="2"
											d="M6 18L18 6M6 6l12 12"
										/>
									</svg>
								</button>
							</div>
						</div>
					{/each}
				</div>
			{/if}
		</div>

		<!-- Projects Section -->
		<div class="mb-6 card-padded">
			<div class="mb-4 flex items-center justify-between">
				<h3 class="text-sm font-medium text-theme-muted">Projects</h3>
				<button
					onclick={() => (showAddProjectsModal = true)}
					class="flex items-center gap-1.5 rounded-lg bg-accent-500/10 px-3 py-1.5 text-sm font-medium text-accent-600 transition-colors hover:bg-accent-500/20 dark:text-accent-400"
				>
					<svg class="h-4 w-4" 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>
					Add Projects
				</button>
			</div>

			{#if report.projects.length === 0}
				<p class="text-sm text-theme-muted italic">No projects added to 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>
								<button
									onclick={() => removeProject(project.id)}
									class="rounded p-1 text-theme-muted transition-colors hover:bg-error-500/10 hover:text-error-600 dark:hover:text-error-400"
									title="Remove project"
								>
									<svg class="h-4 w-4" style="fill: none" stroke="currentColor" viewBox="0 0 24 24">
										<path
											stroke-linecap="round"
											stroke-linejoin="round"
											stroke-width="2"
											d="M6 18L18 6M6 6l12 12"
										/>
									</svg>
								</button>
							</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}

		<!-- Danger Zone -->
		<div
			class="rounded-lg border border-red-200 bg-red-50 p-6 dark:border-red-800 dark:bg-red-900/20"
		>
			<h2 class="mb-2 text-lg font-semibold text-red-700 dark:text-red-400">Danger Zone</h2>
			<p class="mb-4 text-sm text-red-600 dark:text-red-300">
				Deleting this report will permanently remove it. This action cannot be undone.
			</p>
			<button
				onclick={() => (showDeleteModal = true)}
				class="rounded-lg bg-red-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-red-700"
			>
				Delete Report
			</button>
		</div>
	</ContentContainer>
</div>

<DeleteConfirmModal
	bind:open={showDeleteModal}
	title="Delete Report"
	message="Are you sure you want to delete this report? This action cannot be undone."
	onconfirm={handleDelete}
	oncancel={() => {}}
	loading={isDeleting}
/>

<AddServicesModal
	bind:open={showAddServicesModal}
	{report}
	teamMemberId={report.teamMemberId}
	{accountLookup}
	onSuccess={handleServicesUpdated}
/>

<AddProjectsModal
	bind:open={showAddProjectsModal}
	{report}
	teamMemberId={report.teamMemberId}
	{accountLookup}
	{customerLookup}
	onSuccess={handleProjectsUpdated}
/>
