<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 { InvoiceListItem, InvoiceStatus } from '$lib/graphql/queries/invoices';
	import type { CustomerListItem } from '$lib/graphql/queries/customers';
	import { CREATE_INVOICE, type CreateInvoiceInput } from '$lib/graphql/mutations/invoices';

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

	let invoices = $derived((data.invoices.items ?? []) as InvoiceListItem[]);
	let customers = $derived((data.customers ?? []) as CustomerListItem[]);

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

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

	$effect(() => {
		filterCustomerId = data.customerId ?? '';
		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: InvoiceStatus): string {
		switch (status) {
			case 'DRAFT':
				return 'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-300';
			case 'SENT':
				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';
			case 'OVERDUE':
				return 'bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400';
			case 'CANCELLED':
				return 'bg-gray-100 text-gray-500 dark:bg-gray-800 dark:text-gray-500';
			default:
				return 'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-300';
		}
	}

	function applyFilters() {
		const params = new URLSearchParams();
		if (filterCustomerId) params.set('customerId', filterCustomerId);
		if (filterStatus) params.set('status', filterStatus);
		goto(`/admin/invoices?${params.toString()}`);
	}

	function clearFilters() {
		filterCustomerId = '';
		filterStatus = '';
		goto('/admin/invoices');
	}

	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];
		createCustomerId = '';
		createError = '';
		showCreateModal = true;
	}

	async function handleCreateInvoice() {
		if (!createCustomerId || !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: CreateInvoiceInput = {
				customerId: createCustomerId,
				startDate: createStartDate,
				endDate: createEndDate
			};

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

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

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

<div class="py-8">
	<ContentContainer>
		<!-- Header -->
		<AdminDashboardHeader
			title="Invoices"
			subtitle="{data.invoices.totalCount} invoice{data.invoices.totalCount !== 1 ? 's' : ''}"
		>
			{#snippet actions()}
				<a
					href="/admin/invoices/wave"
					class="btn-secondary flex w-full items-center justify-center gap-2 sm:w-auto sm:justify-start"
				>
					<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="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>
					Wave
				</a>
				<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 Invoice
				</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">Customer</span>
				<select
					bind:value={filterCustomerId}
					class="w-full rounded-lg border border-theme bg-theme px-3 py-2 text-theme"
				>
					<option value="">All Customers</option>
					{#each customers as customer}
						<option value={customer.id}>{customer.name}</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="SENT">Sent</option>
					<option value="PAID">Paid</option>
					<option value="OVERDUE">Overdue</option>
					<option value="CANCELLED">Cancelled</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>

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

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

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

						<!-- Total Amount -->
						<div class="mt-2 text-right">
							<span class="text-lg font-bold text-accent6-600 dark:text-accent6-400">
								{formatCurrency(invoice.totalAmount)}
							</span>
						</div>
					</a>
				{/each}
			</div>

			<!-- Pagination -->
			<Pagination
				currentPage={data.page}
				totalCount={data.invoices.totalCount}
				limit={data.limit}
				hasNextPage={data.invoices.hasNextPage}
			/>
		{:else}
			<!-- No invoices -->
			<div class="rounded-lg border border-dashed border-theme 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 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>
				<h3 class="mt-4 text-lg font-medium text-theme">No invoices yet</h3>
				<p class="mt-2 text-theme-secondary">Create an invoice for a customer to track billing.</p>
				<button type="button" class="mt-4 btn-primary" onclick={openCreateModal}>
					Create Invoice
				</button>
			</div>
		{/if}
	</ContentContainer>
</div>

<!-- Create Invoice 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 Invoice</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();
					handleCreateInvoice();
				}}
			>
				<label class="mb-4 block">
					<span class="mb-1 block text-sm font-medium text-theme">Customer</span>
					<select
						bind:value={createCustomerId}
						class="w-full rounded-lg border border-theme bg-theme px-3 py-2 text-theme"
						required
					>
						<option value="">Select customer...</option>
						{#each customers as customer}
							<option value={customer.id}>{customer.name}</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 Invoice'}
					</button>
				</div>
			</form>
		</div>
	</div>
{/if}
