<script lang="ts">
	import { goto } from '$app/navigation';
	import { client } from '$lib/graphql/client';
	import type { PageData } from './$types';
	import { ContentContainer } from '$lib/components/layout';
	import { Pagination, AdminDashboardHeader } from '$lib/components/admin';
	import type { ReportListItem, ReportStatus } from '$lib/graphql/queries/reports';
	import type { TeamProfile } from '$lib/graphql/queries/team';
	import { CREATE_REPORT, type CreateReportInput } from '$lib/graphql/mutations/reports';

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

	let reports = $derived((data.reports.items ?? []) as ReportListItem[]);
	let teamProfiles = $derived((data.teamProfiles ?? []) as TeamProfile[]);

	// Create modal state
	let showCreateModal = $state(false);
	let createTeamProfileId = $state('');
	let createStartDate = $state('');
	let createEndDate = $state('');
	let isCreating = $state(false);
	let createError = $state('');

	// Filter state - use $effect to sync from URL params
	let filterTeamProfileId = $state('');
	let filterStatus = $state('');

	$effect(() => {
		filterTeamProfileId = data.teamProfileId ?? '';
		filterStatus = data.status ?? '';
	});

	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 applyFilters() {
		const params = new URLSearchParams();
		if (filterTeamProfileId) params.set('teamProfileId', filterTeamProfileId);
		if (filterStatus) params.set('status', filterStatus);
		goto(`/admin/reports?${params.toString()}`);
	}

	function clearFilters() {
		filterTeamProfileId = '';
		filterStatus = '';
		goto('/admin/reports');
	}

	function openCreateModal() {
		// Set default dates to current month
		const now = new Date();
		const year = now.getFullYear();
		const month = now.getMonth();
		const firstDay = new Date(year, month, 1);
		const lastDay = new Date(year, month + 1, 0);

		createStartDate = firstDay.toISOString().split('T')[0];
		createEndDate = lastDay.toISOString().split('T')[0];
		createTeamProfileId = '';
		createError = '';
		showCreateModal = true;
	}

	async function handleCreateReport() {
		if (!createTeamProfileId || !createStartDate || !createEndDate) {
			createError = 'Please fill in all fields';
			return;
		}

		if (createEndDate < createStartDate) {
			createError = 'End date must be on or after start date';
			return;
		}

		isCreating = true;
		createError = '';

		try {
			const input: CreateReportInput = {
				teamProfileId: createTeamProfileId,
				startDate: createStartDate,
				endDate: createEndDate
			};

			const result = await client.mutate<{ createReport: { id: string } }>({
				mutation: CREATE_REPORT,
				variables: { input }
			});

			if (result.data?.createReport?.id) {
				showCreateModal = false;
				goto(`/admin/reports/${result.data.createReport.id}`);
			}
		} catch (err) {
			createError = err instanceof Error ? err.message : 'Failed to create report';
		} finally {
			isCreating = false;
		}
	}
</script>

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

<div class="py-8">
	<ContentContainer>
		<!-- Header -->
		<AdminDashboardHeader
			title="Labor Reports"
			subtitle="{data.reports.totalCount} report{data.reports.totalCount !== 1 ? 's' : ''}"
		>
			{#snippet actions()}
				<button
					type="button"
					class="btn-primary flex w-full items-center justify-center gap-2 sm:w-auto sm:justify-start"
					onclick={openCreateModal}
				>
					<svg class="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
						<path
							stroke-linecap="round"
							stroke-linejoin="round"
							stroke-width="2"
							d="M12 4v16m8-8H4"
						/>
					</svg>
					Create Report
				</button>
			{/snippet}
		</AdminDashboardHeader>

		<!-- Filters -->
		<div
			class="mb-6 flex flex-col gap-4 rounded-lg border border-theme bg-theme-card p-4 sm:flex-row sm:items-end"
		>
			<label class="flex-1">
				<span class="mb-1 block text-sm font-medium text-theme">Team Member</span>
				<select
					bind:value={filterTeamProfileId}
					class="w-full rounded-lg border border-theme bg-theme px-3 py-2 text-theme"
				>
					<option value="">All Team Members</option>
					{#each teamProfiles as profile}
						<option value={profile.id}>{profile.fullName}</option>
					{/each}
				</select>
			</label>
			<label class="flex-1">
				<span class="mb-1 block text-sm font-medium text-theme">Status</span>
				<select
					bind:value={filterStatus}
					class="w-full rounded-lg border border-theme bg-theme px-3 py-2 text-theme"
				>
					<option value="">All Statuses</option>
					<option value="DRAFT">Draft</option>
					<option value="FINALIZED">Finalized</option>
					<option value="PAID">Paid</option>
				</select>
			</label>
			<div class="flex gap-2">
				<button type="button" class="btn-secondary" onclick={applyFilters}>Apply</button>
				<button type="button" class="btn-ghost" onclick={clearFilters}>Clear</button>
			</div>
		</div>

		<!-- Reports List -->
		{#if reports.length > 0}
			<div class="mb-6 grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-3">
				{#each reports as report (report.id)}
					<a href="/admin/reports/{report.id}" class="block card-report">
						<!-- Team Member -->
						<div class="flex items-center justify-between">
							<h2 class="truncate font-semibold text-theme">
								{report.teamProfile?.fullName ?? 'Unknown'}
							</h2>
							<span
								class="shrink-0 rounded-full px-2 py-0.5 text-xs font-semibold {getStatusBadgeClass(
									report.status
								)}"
							>
								{report.status}
							</span>
						</div>

						<!-- Date Range -->
						<p class="mt-1 text-sm text-theme-secondary">
							{formatDateRange(report.startDate, report.endDate)}
						</p>

						<!-- Stats -->
						<div class="mt-3 flex items-center justify-between text-sm">
							<span class="text-theme-muted">
								{report.serviceCount} service{report.serviceCount !== 1 ? 's' : ''},
								{report.projectCount} project{report.projectCount !== 1 ? 's' : ''}
							</span>
						</div>

						<!-- Total Labor -->
						<div class="mt-2 text-right">
							<span class="text-lg font-bold text-accent2-600 dark:text-accent2-400">
								{formatCurrency(report.totalLabor)}
							</span>
						</div>
					</a>
				{/each}
			</div>

			<!-- Pagination -->
			<Pagination
				currentPage={data.page}
				totalCount={data.reports.totalCount}
				limit={data.limit}
				hasNextPage={data.reports.hasNextPage}
			/>
		{:else}
			<!-- No reports -->
			<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 reports yet</h3>
				<p class="mt-2 text-theme-secondary">
					Create a report for a team member to track their labor.
				</p>
				<button type="button" class="mt-4 btn-primary" onclick={openCreateModal}>
					Create Report
				</button>
			</div>
		{/if}
	</ContentContainer>
</div>

<!-- Create Report Modal -->
{#if showCreateModal}
	<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={() => (showCreateModal = 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">Create New Report</h2>

			{#if createError}
				<div
					class="mb-4 rounded-lg bg-red-100 p-3 text-sm text-red-700 dark:bg-red-900/30 dark:text-red-400"
				>
					{createError}
				</div>
			{/if}

			<form
				onsubmit={(e) => {
					e.preventDefault();
					handleCreateReport();
				}}
			>
				<label class="mb-4 block">
					<span class="mb-1 block text-sm font-medium text-theme">Team Member</span>
					<select
						bind:value={createTeamProfileId}
						class="w-full rounded-lg border border-theme bg-theme px-3 py-2 text-theme"
						required
					>
						<option value="">Select team member...</option>
						{#each teamProfiles as profile}
							<option value={profile.id}>{profile.fullName}</option>
						{/each}
					</select>
				</label>

				<div class="mb-4 grid grid-cols-2 gap-4">
					<label class="block">
						<span class="mb-1 block text-sm font-medium text-theme">Start Date</span>
						<input
							type="date"
							bind:value={createStartDate}
							class="w-full rounded-lg border border-theme bg-theme px-3 py-2 text-theme"
							required
						/>
					</label>
					<label class="block">
						<span class="mb-1 block text-sm font-medium text-theme">End Date</span>
						<input
							type="date"
							bind:value={createEndDate}
							class="w-full rounded-lg border border-theme bg-theme px-3 py-2 text-theme"
							required
						/>
					</label>
				</div>

				<div class="flex justify-end gap-3">
					<button
						type="button"
						class="btn-ghost"
						onclick={() => (showCreateModal = false)}
						disabled={isCreating}
					>
						Cancel
					</button>
					<button type="submit" class="btn-primary" disabled={isCreating}>
						{isCreating ? 'Creating...' : 'Create Report'}
					</button>
				</div>
			</form>
		</div>
	</div>
{/if}
