<script lang="ts">
	import { goto, invalidateAll } from '$app/navigation';
	import { client } from '$lib/graphql/client';
	import type { PageData } from './$types';
	import { ContentContainer } from '$lib/components/layout';
	import { PageHeader, SectionHeader } from '$lib/components/admin';
	import type {
		ReportDetail,
		ReportStatus,
		EligibleService,
		EligibleProject
	} from '$lib/graphql/queries/reports';
	import {
		UPDATE_REPORT,
		DELETE_REPORT,
		ADD_SERVICE_TO_REPORT,
		ADD_PROJECT_TO_REPORT,
		REMOVE_SERVICE_FROM_REPORT,
		REMOVE_PROJECT_FROM_REPORT,
		ADD_ALL_ELIGIBLE_SERVICES,
		ADD_ALL_ELIGIBLE_PROJECTS
	} from '$lib/graphql/mutations/reports';

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

	let report = $derived(data.report as ReportDetail);
	let eligibleServices = $derived(data.eligibleServices as EligibleService[]);
	let eligibleProjects = $derived(data.eligibleProjects as EligibleProject[]);

	// State
	let isUpdating = $state(false);
	let isDeleting = $state(false);
	let showDeleteConfirm = $state(false);
	let showAddServicesModal = $state(false);
	let showAddProjectsModal = $state(false);
	let addingServiceId = $state<string | null>(null);
	let addingProjectId = $state<string | null>(null);
	let removingId = $state<string | null>(null);

	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', {
			weekday: 'short',
			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';
		}
	}

	async function updateStatus(newStatus: ReportStatus) {
		isUpdating = true;
		try {
			await client.mutate({
				mutation: UPDATE_REPORT,
				variables: { id: report.id, input: { status: newStatus } }
			});
			await invalidateAll();
		} catch (err) {
			console.error('Failed to update status:', err);
		} finally {
			isUpdating = false;
		}
	}

	async function handleDelete() {
		isDeleting = true;
		try {
			await client.mutate({
				mutation: DELETE_REPORT,
				variables: { id: report.id }
			});
			goto('/admin/reports');
		} catch (err) {
			console.error('Failed to delete report:', err);
		} finally {
			isDeleting = false;
			showDeleteConfirm = false;
		}
	}

	async function addService(serviceId: string) {
		addingServiceId = serviceId;
		try {
			await client.mutate({
				mutation: ADD_SERVICE_TO_REPORT,
				variables: { reportId: report.id, serviceId }
			});
			await invalidateAll();
		} catch (err) {
			console.error('Failed to add service:', err);
		} finally {
			addingServiceId = null;
		}
	}

	async function addProject(projectId: string) {
		addingProjectId = projectId;
		try {
			await client.mutate({
				mutation: ADD_PROJECT_TO_REPORT,
				variables: { reportId: report.id, projectId }
			});
			await invalidateAll();
		} catch (err) {
			console.error('Failed to add project:', err);
		} finally {
			addingProjectId = null;
		}
	}

	async function removeService(id: string) {
		removingId = id;
		try {
			await client.mutate({
				mutation: REMOVE_SERVICE_FROM_REPORT,
				variables: { id }
			});
			await invalidateAll();
		} catch (err) {
			console.error('Failed to remove service:', err);
		} finally {
			removingId = null;
		}
	}

	async function removeProject(id: string) {
		removingId = id;
		try {
			await client.mutate({
				mutation: REMOVE_PROJECT_FROM_REPORT,
				variables: { id }
			});
			await invalidateAll();
		} catch (err) {
			console.error('Failed to remove project:', err);
		} finally {
			removingId = null;
		}
	}

	async function addAllServices() {
		isUpdating = true;
		try {
			await client.mutate({
				mutation: ADD_ALL_ELIGIBLE_SERVICES,
				variables: { reportId: report.id }
			});
			await invalidateAll();
			showAddServicesModal = false;
		} catch (err) {
			console.error('Failed to add all services:', err);
		} finally {
			isUpdating = false;
		}
	}

	async function addAllProjects() {
		isUpdating = true;
		try {
			await client.mutate({
				mutation: ADD_ALL_ELIGIBLE_PROJECTS,
				variables: { reportId: report.id }
			});
			await invalidateAll();
			showAddProjectsModal = false;
		} catch (err) {
			console.error('Failed to add all projects:', err);
		} finally {
			isUpdating = false;
		}
	}
</script>

<svelte:head>
	<title>{report.teamProfile?.fullName ?? 'Report'} - Reports - Admin - Nexus</title>
</svelte:head>

<div class="py-8">
	<ContentContainer>
		<PageHeader
			title={report.teamProfile?.fullName ?? 'Unknown'}
			subtitle={formatDateRange(report.startDate, report.endDate)}
			colorScheme="accent2"
			backHref="/admin/reports"
		>
			<span
				class="rounded-full px-3 py-1 text-sm font-semibold {getStatusBadgeClass(report.status)}"
			>
				{report.status}
			</span>
		</PageHeader>

		<!-- Status Actions -->
		<div class="mb-6 flex flex-wrap gap-2">
			{#if report.status === 'DRAFT'}
				<button
					type="button"
					class="btn-accent"
					onclick={() => updateStatus('FINALIZED')}
					disabled={isUpdating}
				>
					Finalize
				</button>
				<button
					type="button"
					class="btn-ghost text-red-600 hover:bg-red-50 dark:text-red-400 dark:hover:bg-red-900/20"
					onclick={() => (showDeleteConfirm = true)}
				>
					Delete
				</button>
			{:else if report.status === 'FINALIZED'}
				<button
					type="button"
					class="btn-primary"
					onclick={() => updateStatus('PAID')}
					disabled={isUpdating}
				>
					Mark as Paid
				</button>
				<button
					type="button"
					class="btn-ghost"
					onclick={() => updateStatus('DRAFT')}
					disabled={isUpdating}
				>
					Revert to Draft
				</button>
			{:else}
				<button
					type="button"
					class="btn-ghost"
					onclick={() => updateStatus('FINALIZED')}
					disabled={isUpdating}
				>
					Revert to Finalized
				</button>
			{/if}
		</div>

		<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-5 py-3">
					<h2 class="text-lg font-semibold text-theme">Summary</h2>
				</div>
				<div class="grid grid-cols-2 gap-4 p-5 sm:grid-cols-4">
					<div>
						<p class="text-sm font-medium text-theme-muted">Services</p>
						<p class="mt-1 text-xl font-bold text-secondary-600 dark:text-secondary-400">
							{report.serviceCount}
						</p>
						<p class="text-sm text-theme-muted">{formatCurrency(report.servicesTotal)}</p>
					</div>
					<div>
						<p class="text-sm font-medium text-theme-muted">Projects</p>
						<p class="mt-1 text-xl font-bold text-accent-600 dark:text-accent-400">
							{report.projectCount}
						</p>
						<p class="text-sm text-theme-muted">{formatCurrency(report.projectsTotal)}</p>
					</div>
					<div class="col-span-2">
						<p class="text-sm font-medium text-theme-muted">Total Labor</p>
						<p class="mt-1 text-2xl font-bold text-accent2-600 dark:text-accent2-400">
							{formatCurrency(report.totalLabor)}
						</p>
					</div>
				</div>
			</section>

			<!-- Services Section -->
			<section
				class="overflow-hidden rounded-xl border border-accent2-500/20 bg-theme-card shadow-theme-md"
			>
				<div class="section-header-accent2 px-5 py-3">
					{#if report.status === 'DRAFT' && eligibleServices.length > 0}
						<SectionHeader
							title="Services ({report.services.length})"
							buttonText="Add ({eligibleServices.length})"
							onButtonClick={() => (showAddServicesModal = true)}
						/>
					{:else}
						<h2 class="text-lg font-semibold text-theme">Services ({report.services.length})</h2>
					{/if}
				</div>
				<div class="px-5 py-5">
					{#if report.services.length > 0}
						<div class="overflow-x-auto rounded-lg border border-theme">
							<table class="w-full">
								<thead class="bg-theme-secondary">
									<tr
										class="text-left text-xs font-medium tracking-wider text-theme-muted uppercase"
									>
										<th class="px-4 py-2">Date</th>
										<th class="px-4 py-2">Account</th>
										<th class="px-4 py-2">Location</th>
										<th class="px-4 py-2 text-right">Labor Share</th>
										{#if report.status === 'DRAFT'}
											<th class="px-4 py-2"></th>
										{/if}
									</tr>
								</thead>
								<tbody class="divide-theme divide-y">
									{#each report.services as entry (entry.id)}
										<tr>
											<td class="px-4 py-2 text-sm whitespace-nowrap text-theme">
												{formatDate(entry.service?.date ?? '')}
											</td>
											<td class="px-4 py-2 text-sm text-theme">
												{entry.service?.account?.name ?? 'Unknown'}
											</td>
											<td class="px-4 py-2 text-sm text-theme-secondary">
												{entry.service?.accountAddress?.name ??
													entry.service?.accountAddress?.streetAddress ??
													''}
											</td>
											<td
												class="px-4 py-2 text-right text-sm font-medium whitespace-nowrap text-accent2-600 dark:text-accent2-400"
											>
												{formatCurrency(entry.laborShare)}
											</td>
											{#if report.status === 'DRAFT'}
												<td class="px-4 py-2 text-right">
													<button
														type="button"
														class="text-red-600 hover:text-red-800 disabled:opacity-50 dark:text-red-400"
														onclick={() => removeService(entry.id)}
														disabled={removingId === entry.id}
														aria-label="Remove service"
													>
														<svg
															class="h-4 w-4"
															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>
												</td>
											{/if}
										</tr>
									{/each}
								</tbody>
							</table>
						</div>
					{:else}
						<div class="py-6 text-center text-theme-muted">
							No services added yet.
							{#if report.status === 'DRAFT' && eligibleServices.length > 0}
								<button
									type="button"
									class="mx-auto mt-2 block text-secondary-600 hover:text-secondary-700 dark:text-secondary-400"
									onclick={() => (showAddServicesModal = true)}
								>
									Add services
								</button>
							{/if}
						</div>
					{/if}
				</div>
			</section>

			<!-- Projects Section -->
			<section
				class="overflow-hidden rounded-xl border border-accent2-500/20 bg-theme-card shadow-theme-md"
			>
				<div class="section-header-accent2 px-5 py-3">
					{#if report.status === 'DRAFT' && eligibleProjects.length > 0}
						<SectionHeader
							title="Projects ({report.projects.length})"
							buttonText="Add ({eligibleProjects.length})"
							onButtonClick={() => (showAddProjectsModal = true)}
						/>
					{:else}
						<h2 class="text-lg font-semibold text-theme">Projects ({report.projects.length})</h2>
					{/if}
				</div>
				<div class="px-5 py-5">
					{#if report.projects.length > 0}
						<div class="overflow-x-auto rounded-lg border border-theme">
							<table class="w-full">
								<thead class="bg-theme-secondary">
									<tr
										class="text-left text-xs font-medium tracking-wider text-theme-muted uppercase"
									>
										<th class="px-4 py-2">Date</th>
										<th class="px-4 py-2">Project</th>
										<th class="px-4 py-2">Customer</th>
										<th class="px-4 py-2 text-right">Labor Share</th>
										{#if report.status === 'DRAFT'}
											<th class="px-4 py-2"></th>
										{/if}
									</tr>
								</thead>
								<tbody class="divide-theme divide-y">
									{#each report.projects as entry (entry.id)}
										<tr>
											<td class="px-4 py-2 text-sm whitespace-nowrap text-theme">
												{formatDate(entry.project?.date ?? '')}
											</td>
											<td class="px-4 py-2 text-sm text-theme">
												{entry.project?.name ?? 'Unknown'}
											</td>
											<td class="px-4 py-2 text-sm text-theme-secondary">
												{entry.project?.customer?.name ?? ''}
											</td>
											<td
												class="px-4 py-2 text-right text-sm font-medium whitespace-nowrap text-accent2-600 dark:text-accent2-400"
											>
												{formatCurrency(entry.laborShare)}
											</td>
											{#if report.status === 'DRAFT'}
												<td class="px-4 py-2 text-right">
													<button
														type="button"
														class="text-red-600 hover:text-red-800 disabled:opacity-50 dark:text-red-400"
														onclick={() => removeProject(entry.id)}
														disabled={removingId === entry.id}
														aria-label="Remove project"
													>
														<svg
															class="h-4 w-4"
															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>
												</td>
											{/if}
										</tr>
									{/each}
								</tbody>
							</table>
						</div>
					{:else}
						<div class="py-6 text-center text-theme-muted">
							No projects added yet.
							{#if report.status === 'DRAFT' && eligibleProjects.length > 0}
								<button
									type="button"
									class="mx-auto mt-2 block text-accent-600 hover:text-accent-700 dark:text-accent-400"
									onclick={() => (showAddProjectsModal = true)}
								>
									Add projects
								</button>
							{/if}
						</div>
					{/if}
				</div>
			</section>
		</div>
	</ContentContainer>
</div>

<!-- Add Services Modal -->
{#if showAddServicesModal}
	<div class="fixed inset-0 z-50 flex items-center justify-center p-4">
		<button
			type="button"
			class="absolute inset-0 bg-black/50"
			onclick={() => (showAddServicesModal = false)}
			aria-label="Close modal"
		></button>
		<div
			class="relative max-h-[80vh] w-full max-w-2xl overflow-hidden rounded-xl border border-theme bg-theme-card shadow-xl"
		>
			<div class="flex items-center justify-between border-b border-theme p-4">
				<h2 class="text-lg font-semibold text-theme">Add Services</h2>
				<button
					type="button"
					class="btn-primary text-sm"
					onclick={addAllServices}
					disabled={isUpdating}
				>
					{isUpdating ? 'Adding...' : `Add All (${eligibleServices.length})`}
				</button>
			</div>
			<div class="max-h-[60vh] overflow-y-auto p-4">
				{#if eligibleServices.length > 0}
					<div class="space-y-2">
						{#each eligibleServices as service (service.serviceId)}
							<div class="flex items-center justify-between rounded-lg border border-theme p-3">
								<div>
									<p class="font-medium text-theme">
										{service.service?.account?.name ?? 'Unknown'}
									</p>
									<p class="text-sm text-theme-secondary">
										{formatDate(service.date)} - {service.service?.accountAddress?.city ?? ''}
									</p>
									<p class="text-xs text-theme-muted">
										{formatCurrency(service.laborTotal)} ÷ {service.teamMemberCount} = {formatCurrency(
											service.laborShare
										)}
									</p>
								</div>
								<button
									type="button"
									class="btn-secondary text-sm"
									onclick={() => addService(service.serviceId)}
									disabled={addingServiceId === service.serviceId}
								>
									{addingServiceId === service.serviceId ? 'Adding...' : 'Add'}
								</button>
							</div>
						{/each}
					</div>
				{:else}
					<p class="text-center text-theme-muted">No eligible services available.</p>
				{/if}
			</div>
			<div class="border-t border-theme p-4">
				<button
					type="button"
					class="btn-ghost w-full"
					onclick={() => (showAddServicesModal = false)}
				>
					Close
				</button>
			</div>
		</div>
	</div>
{/if}

<!-- Add Projects Modal -->
{#if showAddProjectsModal}
	<div class="fixed inset-0 z-50 flex items-center justify-center p-4">
		<button
			type="button"
			class="absolute inset-0 bg-black/50"
			onclick={() => (showAddProjectsModal = false)}
			aria-label="Close modal"
		></button>
		<div
			class="relative max-h-[80vh] w-full max-w-2xl overflow-hidden rounded-xl border border-theme bg-theme-card shadow-xl"
		>
			<div class="flex items-center justify-between border-b border-theme p-4">
				<h2 class="text-lg font-semibold text-theme">Add Projects</h2>
				<button
					type="button"
					class="btn-primary text-sm"
					onclick={addAllProjects}
					disabled={isUpdating}
				>
					{isUpdating ? 'Adding...' : `Add All (${eligibleProjects.length})`}
				</button>
			</div>
			<div class="max-h-[60vh] overflow-y-auto p-4">
				{#if eligibleProjects.length > 0}
					<div class="space-y-2">
						{#each eligibleProjects as project (project.projectId)}
							<div class="flex items-center justify-between rounded-lg border border-theme p-3">
								<div>
									<p class="font-medium text-theme">
										{project.project?.name ?? 'Unknown'}
									</p>
									<p class="text-sm text-theme-secondary">
										{formatDate(project.date)} - {project.project?.customer?.name ?? ''}
									</p>
									<p class="text-xs text-theme-muted">
										{formatCurrency(project.laborTotal)} ÷ {project.teamMemberCount} = {formatCurrency(
											project.laborShare
										)}
									</p>
								</div>
								<button
									type="button"
									class="btn-secondary text-sm"
									onclick={() => addProject(project.projectId)}
									disabled={addingProjectId === project.projectId}
								>
									{addingProjectId === project.projectId ? 'Adding...' : 'Add'}
								</button>
							</div>
						{/each}
					</div>
				{:else}
					<p class="text-center text-theme-muted">No eligible projects available.</p>
				{/if}
			</div>
			<div class="border-t border-theme p-4">
				<button
					type="button"
					class="btn-ghost w-full"
					onclick={() => (showAddProjectsModal = false)}
				>
					Close
				</button>
			</div>
		</div>
	</div>
{/if}

<!-- Delete Confirmation Modal -->
{#if showDeleteConfirm}
	<div class="fixed inset-0 z-50 flex items-center justify-center p-4">
		<button
			type="button"
			class="absolute inset-0 bg-black/50"
			onclick={() => (showDeleteConfirm = false)}
			aria-label="Close modal"
		></button>
		<div
			class="relative w-full max-w-md rounded-xl border border-theme bg-theme-card p-6 shadow-xl"
		>
			<h2 class="mb-4 text-lg font-semibold text-theme">Delete Report?</h2>
			<p class="mb-6 text-theme-secondary">
				Are you sure you want to delete this report? This action cannot be undone.
			</p>
			<div class="flex justify-end gap-3">
				<button
					type="button"
					class="btn-ghost"
					onclick={() => (showDeleteConfirm = false)}
					disabled={isDeleting}
				>
					Cancel
				</button>
				<button
					type="button"
					class="btn-primary bg-red-600 hover:bg-red-700"
					onclick={handleDelete}
					disabled={isDeleting}
				>
					{isDeleting ? 'Deleting...' : 'Delete Report'}
				</button>
			</div>
		</div>
	</div>
{/if}
