<script lang="ts">
	import ContentContainer from '$lib/components/layout/ContentContainer.svelte';
	import InvoiceForm from '$lib/components/admin/invoices/InvoiceForm.svelte';
	import { offCanvas } from '$lib/stores/offCanvas.svelte';
	import { goto } from '$app/navigation';
	import { invalidateDashboard } from '$lib/utils/invalidate';
	import { page } from '$app/state';
	import { fromGlobalId } from '$lib/utils/relay';
	import type { PageData } from './$types';

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

	// Auto-open create form if action=create is in URL
	$effect(() => {
		if (page.url.searchParams.get('action') === 'create') {
			showCreateForm();
			// Remove the action param from URL without navigation
			goto('/admin/invoices', { replaceState: true, noScroll: true });
		}
	});

	let customers = $derived(data.customers?.data?.customers ?? []);
	let invoices = $derived(data.invoices ?? []);
	let customerLookup = $derived(data.customerLookup);

	// Sort invoices by date descending (most recent first)
	let sortedInvoices = $derived([...invoices].sort((a, b) => b.date.localeCompare(a.date)));

	// Search and filter
	let searchQuery = $state('');
	let selectedStatus = $state<string>('');
	let selectedCustomerId = $state<string>('');

	// Filter invoices
	let filteredInvoices = $derived.by(() => {
		let filtered = sortedInvoices;

		// Filter by status
		if (selectedStatus) {
			filtered = filtered.filter((i) => i.status === selectedStatus);
		}

		// Filter by customer (comparing UUIDs)
		if (selectedCustomerId) {
			const selectedUuid = fromGlobalId(selectedCustomerId);
			filtered = filtered.filter((i) => i.customerId === selectedUuid);
		}

		// Filter by search query (customer name or date)
		if (searchQuery.trim()) {
			const query = searchQuery.toLowerCase();
			filtered = filtered.filter((i) => {
				const customerName = getCustomerName(i.customerId).toLowerCase();
				const date = formatDate(i.date).toLowerCase();
				return customerName.includes(query) || date.includes(query);
			});
		}

		return filtered;
	});

	// Get customer name from UUID
	function getCustomerName(customerId: string): string {
		return customerLookup.get(customerId)?.customerName ?? 'Unknown';
	}

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

	// Get status badge classes
	function getStatusClasses(status: string): string {
		switch (status) {
			case 'DRAFT':
				return 'bg-gray-500/10 text-gray-600 dark:text-gray-400';
			case 'SENT':
				return 'bg-primary-500/10 text-primary-600 dark:text-primary-400';
			case 'PAID':
				return 'bg-success-500/10 text-success-600 dark:text-success-400';
			case 'OVERDUE':
				return 'bg-error-500/10 text-error-600 dark:text-error-400';
			case 'CANCELLED':
				return 'bg-warning-500/10 text-warning-600 dark:text-warning-400';
			default:
				return 'bg-gray-500/10 text-gray-600 dark:text-gray-400';
		}
	}

	// Get status display label
	function getStatusLabel(status: string): string {
		switch (status) {
			case 'DRAFT':
				return 'Draft';
			case 'SENT':
				return 'Sent';
			case 'PAID':
				return 'Paid';
			case 'OVERDUE':
				return 'Overdue';
			case 'CANCELLED':
				return 'Cancelled';
			default:
				return status;
		}
	}

	// Get payment type label
	function getPaymentTypeLabel(paymentType: string | null): string {
		if (!paymentType) return '';
		switch (paymentType) {
			case 'CHECK':
				return 'Check';
			case 'CREDIT_CARD':
				return 'Credit Card';
			case 'BANK_TRANSFER':
				return 'Bank Transfer';
			case 'CASH':
				return 'Cash';
			default:
				return paymentType;
		}
	}

	function showCreateForm() {
		offCanvas.showRight({
			title: 'Create Invoice',
			content: createFormContent
		});
	}

	async function handleSuccess() {
		await invalidateDashboard();
	}

	// Active customers for filter dropdown
	let activeCustomers = $derived(customers.filter((c) => c.status === 'ACTIVE'));
</script>

{#snippet createFormContent()}
	<InvoiceForm {customers} onSuccess={handleSuccess} />
{/snippet}

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

<div class="py-8">
	<ContentContainer>
		<!-- Header -->
		<div class="mb-8">
			<div class="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
				<div class="flex items-start gap-4">
					<a
						href="/admin"
						class="rounded-lg p-1 text-theme-muted hover:bg-black/5 hover:text-theme dark:hover:bg-white/10"
						aria-label="Go back"
					>
						<svg class="h-5 w-5" style="fill: none" stroke="currentColor" viewBox="0 0 24 24">
							<path
								stroke-linecap="round"
								stroke-linejoin="round"
								stroke-width="2"
								d="M15 19l-7-7 7-7"
							/>
						</svg>
					</a>
					<div>
						<h1 class="text-2xl font-bold text-accent6-600 md:text-3xl dark:text-accent6-400">
							Invoices
						</h1>
						<p class="mt-2 text-theme-secondary">Create and manage customer invoices.</p>
					</div>
				</div>
				<div class="hidden items-center gap-2 sm:flex">
					<a
						href="/admin/invoices/wave"
						class="inline-flex items-center gap-2 rounded-lg border border-accent6-500/30 bg-accent6-500/10 px-4 py-2 text-accent6-600 transition-colors hover:bg-accent6-500/20 dark:text-accent6-400"
					>
						<svg class="h-5 w-5" style="fill: none" stroke="currentColor" viewBox="0 0 24 24">
							<path
								stroke-linecap="round"
								stroke-linejoin="round"
								stroke-width="2"
								d="M13 10V3L4 14h7v7l9-11h-7z"
							/>
						</svg>
						<span>Wave</span>
					</a>
					<button
						type="button"
						onclick={showCreateForm}
						class="inline-flex items-center gap-2 rounded-lg bg-primary-500 px-4 py-2 text-white transition-colors hover:bg-primary-600"
					>
						<svg class="h-5 w-5" 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>
						<span>Create Invoice</span>
					</button>
				</div>
			</div>

			<!-- Mobile action buttons -->
			<div class="mt-4 flex gap-2 sm:hidden">
				<a
					href="/admin/invoices/wave"
					class="flex flex-1 items-center justify-center gap-2 rounded-lg border border-accent6-500/30 bg-accent6-500/10 px-4 py-2.5 text-sm font-medium text-accent6-600 transition-colors hover:bg-accent6-500/20 dark:text-accent6-400"
				>
					<svg class="h-5 w-5" style="fill: none" stroke="currentColor" viewBox="0 0 24 24">
						<path
							stroke-linecap="round"
							stroke-linejoin="round"
							stroke-width="2"
							d="M13 10V3L4 14h7v7l9-11h-7z"
						/>
					</svg>
					<span>Wave</span>
				</a>
				<button
					type="button"
					onclick={showCreateForm}
					class="flex flex-1 items-center justify-center gap-2 rounded-lg bg-primary-500 px-4 py-2.5 text-sm font-medium text-white transition-colors hover:bg-primary-600"
				>
					<svg class="h-5 w-5" 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>
					<span>Create</span>
				</button>
			</div>
		</div>

		<!-- Search and Filter -->
		<div class="mb-6 flex flex-col gap-4 sm:flex-row">
			<!-- Search -->
			<div class="relative flex-1">
				<svg
					class="absolute top-1/2 left-3 h-5 w-5 -translate-y-1/2 text-theme-muted"
					style="fill: none"
					stroke="currentColor"
					viewBox="0 0 24 24"
				>
					<path
						stroke-linecap="round"
						stroke-linejoin="round"
						stroke-width="2"
						d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"
					/>
				</svg>
				<input
					type="text"
					bind:value={searchQuery}
					placeholder="Search invoices..."
					class="placeholder-theme-muted w-full rounded-lg border border-theme bg-theme-card py-2 pr-4 pl-10 text-theme focus:border-primary-500 focus:ring-1 focus:ring-primary-500"
				/>
			</div>

			<!-- Status Filter -->
			<select
				bind:value={selectedStatus}
				class="rounded-lg border border-theme bg-theme-card px-3 py-2 text-theme focus:border-primary-500 focus:ring-1 focus:ring-primary-500 sm:w-40"
			>
				<option value="">All Statuses</option>
				<option value="DRAFT">Draft</option>
				<option value="SENT">Sent</option>
				<option value="PAID">Paid</option>
				<option value="OVERDUE">Overdue</option>
				<option value="CANCELLED">Cancelled</option>
			</select>

			<!-- Customer Filter -->
			<select
				bind:value={selectedCustomerId}
				class="rounded-lg border border-theme bg-theme-card px-3 py-2 text-theme focus:border-primary-500 focus:ring-1 focus:ring-primary-500 sm:w-64"
			>
				<option value="">All Customers</option>
				{#each activeCustomers as customer (customer.id)}
					<option value={customer.id}>{customer.name}</option>
				{/each}
			</select>
		</div>

		<!-- Invoices List -->
		{#if filteredInvoices.length > 0}
			<div class="space-y-4">
				{#each filteredInvoices as invoice (invoice.id)}
					<a href="/admin/invoices/{invoice.id}" class="block">
						<div class="card-invoice">
							<div class="flex items-start justify-between gap-4">
								<div class="min-w-0 flex-1 space-y-2">
									<!-- Customer Name & Date -->
									<div class="flex flex-wrap items-center gap-3">
										<h3 class="text-lg font-semibold text-accent6-600 dark:text-accent6-400">
											{getCustomerName(invoice.customerId)}
										</h3>
										<span
											class={`inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium ${getStatusClasses(invoice.status)}`}
										>
											{getStatusLabel(invoice.status)}
										</span>
									</div>

									<!-- Invoice Details -->
									<div class="flex flex-wrap items-center gap-4 text-sm text-theme-secondary">
										<span class="flex items-center gap-1.5">
											<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="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"
												/>
											</svg>
											{formatDate(invoice.date)}
										</span>

										{#if invoice.status === 'PAID' && invoice.datePaid}
											<span
												class="flex items-center gap-1.5 text-success-600 dark:text-success-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="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"
													/>
												</svg>
												Paid {formatDate(invoice.datePaid)}
											</span>
										{/if}

										{#if invoice.paymentType}
											<span class="flex items-center gap-1.5">
												<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="M3 10h18M7 15h1m4 0h1m-7 4h12a3 3 0 003-3V8a3 3 0 00-3-3H6a3 3 0 00-3 3v8a3 3 0 003 3z"
													/>
												</svg>
												{getPaymentTypeLabel(invoice.paymentType)}
											</span>
										{/if}

										{#if invoice.waveInvoiceId}
											<span class="badge-primary">Linked</span>
										{/if}
									</div>
								</div>

								<!-- Chevron -->
								<svg
									class="mt-1 h-5 w-5 flex-shrink-0 text-theme-muted"
									style="fill: none"
									stroke="currentColor"
									viewBox="0 0 24 24"
								>
									<path
										stroke-linecap="round"
										stroke-linejoin="round"
										stroke-width="2"
										d="M9 5l7 7-7 7"
									/>
								</svg>
							</div>
						</div>
					</a>
				{/each}
			</div>
		{:else if searchQuery || selectedStatus || selectedCustomerId}
			<div class="empty-state">
				<svg
					class="empty-state-icon text-accent6-400"
					style="fill: none"
					stroke="currentColor"
					viewBox="0 0 24 24"
				>
					<path
						stroke-linecap="round"
						stroke-linejoin="round"
						stroke-width="1.5"
						d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"
					/>
				</svg>
				<h2 class="empty-state-title">No Invoices Found</h2>
				<p class="empty-state-text">
					No invoices match your search criteria. Try adjusting your filters.
				</p>
			</div>
		{:else}
			<div class="empty-state">
				<svg
					class="empty-state-icon text-accent6-400"
					style="fill: none"
					stroke="currentColor"
					viewBox="0 0 24 24"
				>
					<path
						stroke-linecap="round"
						stroke-linejoin="round"
						stroke-width="1.5"
						d="M9 12h6m-6 4h6m2 5H7a2 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>
				<h2 class="empty-state-title">No Invoices Yet</h2>
				<p class="empty-state-text">
					Get started by creating your first invoice. Track payments and billing for all your
					customers.
				</p>
				<button
					type="button"
					onclick={showCreateForm}
					class="mt-4 inline-flex items-center gap-2 rounded-lg bg-primary-500 px-4 py-2 text-white transition-colors hover:bg-primary-600"
				>
					<svg class="h-5 w-5" 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>
					<span>Create Invoice</span>
				</button>
			</div>
		{/if}
	</ContentContainer>
</div>
