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

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

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

	// Filter state
	let filterStatus = $state('');

	$effect(() => {
		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 (filterStatus) params.set('status', filterStatus);
		goto(`/team/reports?${params.toString()}`);
	}

	function clearFilters() {
		filterStatus = '';
		goto('/team/reports');
	}
</script>

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

<div class="py-8">
	<ContentContainer>
		<PageHeader
			title="My Reports"
			subtitle="{data.reports.totalCount} report{data.reports.totalCount !== 1 ? 's' : ''}"
			backHref="/team"
			colorScheme="accent2"
		/>

		<!-- 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">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="/team/reports/{report.id}" class="block card-report">
						<!-- Date Range -->
						<div class="flex items-center justify-between">
							<h2 class="font-semibold text-theme">
								{formatDateRange(report.startDate, report.endDate)}
							</h2>
							<span
								class="shrink-0 rounded-full px-2 py-0.5 text-xs font-semibold {getStatusBadgeClass(
									report.status
								)}"
							>
								{report.status}
							</span>
						</div>

						<!-- 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">Your labor reports will appear here once created.</p>
			</div>
		{/if}
	</ContentContainer>
</div>
