<script lang="ts">
	import type { PageData } from './$types';
	import { ContentContainer } from '$lib/components/layout';
	import { CustomerPageHeader } from '$lib/components/customer';
	import { IconChevronRight } from '$lib/components/icons';
	import type { InvoiceStatus } from '$lib/graphql/queries/invoices';

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

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

	function formatDateRange(startDate: string, endDate: string): string {
		const start = new Date(startDate + 'T00:00:00');
		const end = new Date(endDate + 'T00:00:00');
		const opts: Intl.DateTimeFormatOptions = { month: 'short', day: 'numeric' };
		const yearOpts: Intl.DateTimeFormatOptions = { ...opts, year: 'numeric' };

		if (start.getFullYear() === end.getFullYear()) {
			return `${start.toLocaleDateString('en-US', opts)} - ${end.toLocaleDateString('en-US', yearOpts)}`;
		}
		return `${start.toLocaleDateString('en-US', yearOpts)} - ${end.toLocaleDateString('en-US', yearOpts)}`;
	}

	function formatCurrency(amount: number): string {
		return new Intl.NumberFormat('en-US', {
			style: 'currency',
			currency: 'USD',
			minimumFractionDigits: 2
		}).format(amount);
	}

	function getStatusBadgeClass(status: InvoiceStatus): string {
		switch (status) {
			case 'PAID':
				return 'badge-success';
			case 'SENT':
				return 'badge-primary';
			case 'OVERDUE':
				return 'badge-error';
			case 'DRAFT':
				return 'badge-neutral';
			case 'CANCELLED':
				return 'badge-error';
			default:
				return 'badge-neutral';
		}
	}

	function formatStatusLabel(status: InvoiceStatus): string {
		return status.charAt(0) + status.slice(1).toLowerCase();
	}
</script>

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

<div class="py-8">
	<ContentContainer maxWidth="4xl">
		<CustomerPageHeader
			title="Invoices"
			subtitle="View your billing history and invoices."
			backHref="/customer"
			colorScheme="accent2"
		/>

		{#if invoices.length > 0}
			<div class="space-y-3">
				{#each invoices as invoice (invoice.id)}
					<a
						href="/customer/invoices/{invoice.id}"
						class="shadow-theme-sm flex items-center justify-between rounded-xl border border-theme bg-theme-card p-4 transition-all hover:border-accent2-500/30 hover:shadow-theme-md"
					>
						<div class="min-w-0 flex-1">
							<div class="flex flex-wrap items-center gap-2">
								<span class={getStatusBadgeClass(invoice.status)}>
									{formatStatusLabel(invoice.status)}
								</span>
							</div>
							<p class="mt-1 font-medium text-theme">
								{formatDateRange(invoice.startDate, invoice.endDate)}
							</p>
							<div class="mt-1 flex flex-wrap gap-3 text-sm text-theme-muted">
								{#if invoice.revenueCount > 0}
									<span>{invoice.revenueCount} service{invoice.revenueCount !== 1 ? 's' : ''}</span>
								{/if}
								{#if invoice.projectCount > 0}
									<span>{invoice.projectCount} project{invoice.projectCount !== 1 ? 's' : ''}</span>
								{/if}
							</div>
						</div>
						<div class="flex items-center gap-3">
							<span class="text-lg font-semibold text-theme">
								{formatCurrency(invoice.totalAmount)}
							</span>
							<IconChevronRight class="h-5 w-5 shrink-0 text-theme-muted" />
						</div>
					</a>
				{/each}
			</div>
		{:else}
			<div class="empty-state">
				<svg class="empty-state-icon" 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</h2>
				<p class="empty-state-text">You don't have any invoices yet.</p>
			</div>
		{/if}
	</ContentContainer>
</div>
