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

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

	let invoice = $derived(data.invoice as InvoiceDetail);

	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', {
			weekday: 'short',
			month: 'short',
			day: 'numeric',
			year: 'numeric'
		});
	}

	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 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>Invoice - {formatDateRange(invoice.startDate, invoice.endDate)} - Nexus</title>
</svelte:head>

<div class="py-8">
	<ContentContainer maxWidth="4xl">
		<CustomerPageHeader
			title={formatDateRange(invoice.startDate, invoice.endDate)}
			subtitle={formatCurrency(invoice.totalAmount)}
			backHref="/customer/invoices"
			colorScheme="accent2"
		>
			<span class={getStatusBadgeClass(invoice.status)}>
				{formatStatusLabel(invoice.status)}
			</span>
		</CustomerPageHeader>

		<div class="space-y-6">
			<!-- Summary Section -->
			<CustomerSectionContainer title="Summary" colorScheme="accent2">
				<div class="grid grid-cols-2 gap-4 sm:grid-cols-3">
					<div>
						<p class="text-sm font-medium text-theme-muted">Services</p>
						<p class="mt-1 text-xl font-bold text-secondary-600 dark:text-secondary-400">
							{invoice.revenueCount}
						</p>
						<p class="text-sm text-theme-muted">{formatCurrency(invoice.revenuesTotal)}</p>
					</div>
					<div>
						<p class="text-sm font-medium text-theme-muted">Projects</p>
						<p class="mt-1 text-xl font-bold text-accent-600 dark:text-accent-400">
							{invoice.projectCount}
						</p>
						<p class="text-sm text-theme-muted">{formatCurrency(invoice.projectsTotal)}</p>
					</div>
					<div class="col-span-2 sm:col-span-1">
						<p class="text-sm font-medium text-theme-muted">Total</p>
						<p class="mt-1 text-xl font-bold text-accent2-600 dark:text-accent2-400">
							{formatCurrency(invoice.totalAmount)}
						</p>
					</div>
				</div>
			</CustomerSectionContainer>

			<!-- Revenues Section -->
			{#if invoice.revenues.length > 0}
				<CustomerSectionContainer
					title="Services ({invoice.revenues.length})"
					colorScheme="accent2"
				>
					<div class="space-y-3">
						{#each invoice.revenues as entry (entry.id)}
							<div class="bg-theme-secondary/50 rounded-lg border border-theme p-4">
								<div class="flex items-start justify-between">
									<div class="flex-1">
										<p class="font-medium text-theme">{entry.account?.name ?? 'Unknown Account'}</p>
										<p class="mt-1 text-sm text-theme-secondary">
											{entry.revenue?.startDate ? formatDate(entry.revenue.startDate) : ''} - {entry
												.revenue?.endDate
												? formatDate(entry.revenue.endDate)
												: 'Ongoing'}
										</p>
									</div>
									<span class="font-medium text-accent2-600 dark:text-accent2-400">
										{formatCurrency(entry.amount)}
									</span>
								</div>
							</div>
						{/each}
					</div>
				</CustomerSectionContainer>
			{/if}

			<!-- Projects Section -->
			{#if invoice.projects.length > 0}
				<CustomerSectionContainer
					title="Projects ({invoice.projects.length})"
					colorScheme="accent2"
				>
					<div class="space-y-3">
						{#each invoice.projects as entry (entry.id)}
							<div class="bg-theme-secondary/50 rounded-lg border border-theme p-4">
								<div class="flex items-start justify-between">
									<div class="flex-1">
										<p class="font-medium text-theme">{entry.project?.name ?? 'Unknown'}</p>
										<p class="mt-1 text-sm text-theme-secondary">
											{formatDate(entry.project?.date ?? '')}
											{#if entry.account?.name}
												<span class="text-theme-muted"> - {entry.account.name}</span>
											{/if}
										</p>
										{#if entry.project?.formattedAddress}
											<p class="mt-1 text-sm text-theme-muted">{entry.project.formattedAddress}</p>
										{/if}
									</div>
									<span class="font-medium text-accent2-600 dark:text-accent2-400">
										{formatCurrency(entry.amount)}
									</span>
								</div>
							</div>
						{/each}
					</div>
				</CustomerSectionContainer>
			{/if}

			<!-- Empty state if no line items -->
			{#if invoice.revenues.length === 0 && invoice.projects.length === 0}
				<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 items</h2>
					<p class="empty-state-text">This invoice doesn't have any line items yet.</p>
				</div>
			{/if}
		</div>
	</ContentContainer>
</div>
