<script lang="ts">
	import ContentContainer from '$lib/components/layout/ContentContainer.svelte';
	import CustomerPageHeader from '$lib/components/customer/CustomerPageHeader.svelte';
	import MonthSelector from '$lib/components/team/MonthSelector.svelte';
	import { formatDate, getCurrentMonth } from '$lib/utils/date';
	import type { PageData } from './$types';
	import type { CustomerInvoices$result } from '$houdini';

	type Invoice = CustomerInvoices$result['invoices'][number];

	type LayoutData = PageData & {
		currentMonth?: string;
		invoices?: Invoice[];
		customerNames?: Record<string, string>;
		customerIds?: string[];
	};

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

	let currentMonth = $derived(data.currentMonth ?? getCurrentMonth());
	let invoices = $derived(data.invoices ?? []);
	let customerNames = $derived(data.customerNames ?? ({} as Record<string, string>));
	let hasMultipleCustomers = $derived((data.customerIds?.length ?? 0) > 1);

	type FilterType = 'all' | 'sent' | 'paid';
	let activeFilter = $state<FilterType>('all');

	// Filter by month (client-side since API doesn't support date filter)
	let monthFilteredInvoices = $derived(
		invoices.filter((invoice) => {
			// invoice.date is YYYY-MM-DD, currentMonth is YYYY-MM
			return invoice.date.startsWith(currentMonth);
		})
	);

	let filteredInvoices = $derived(
		monthFilteredInvoices.filter((invoice) => {
			if (activeFilter === 'all') return true;
			// 'sent' tab shows invoices that are not yet paid or cancelled (i.e., pending)
			if (activeFilter === 'sent')
				return invoice.status !== 'PAID' && invoice.status !== 'CANCELLED';
			if (activeFilter === 'paid') return invoice.status === 'PAID';
			return true;
		})
	);

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

	function getCustomerName(customerId: string): string {
		// customerId from invoice is already a UUID, not a Relay ID
		return customerNames[customerId] ?? 'Unknown';
	}

	function getStatusBadge(status: string): { text: string; classes: string } {
		switch (status) {
			case 'PAID':
				return {
					text: 'Paid',
					classes: 'bg-success-100 text-success-700 dark:bg-success-900/30 dark:text-success-400'
				};
			case 'CANCELLED':
				return {
					text: 'Cancelled',
					classes: 'bg-black/10 text-theme-secondary dark:bg-white/10'
				};
			case 'OVERDUE':
				return {
					text: 'Overdue',
					classes: 'bg-error-100 text-error-700 dark:bg-error-900/30 dark:text-error-400'
				};
			case 'DRAFT':
			default:
				// Draft and other statuses show as pending
				return {
					text: 'Pending',
					classes: 'bg-warning-100 text-warning-700 dark:bg-warning-900/30 dark:text-warning-400'
				};
		}
	}

	const filterTabs: { key: FilterType; label: string }[] = [
		{ key: 'all', label: 'All' },
		{ key: 'sent', label: 'Pending' },
		{ key: 'paid', label: 'Paid' }
	];
</script>

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

<div class="py-8">
	<ContentContainer>
		<CustomerPageHeader
			title="Invoices"
			subtitle="View your invoices and payment history."
			colorScheme="accent6"
		/>

		<!-- Month Selector and Filter Tabs -->
		<div class="mb-6 flex flex-wrap items-center justify-between gap-4">
			<MonthSelector value={currentMonth} />
			<div class="flex gap-2">
				{#each filterTabs as tab (tab.key)}
					<button
						type="button"
						onclick={() => (activeFilter = tab.key)}
						class="rounded-lg px-4 py-2 text-sm font-medium transition-colors {activeFilter ===
						tab.key
							? 'bg-accent6-500 text-white'
							: 'bg-black/5 text-theme-secondary hover:bg-black/10 dark:bg-white/10 dark:hover:bg-white/15'}"
					>
						{tab.label}
					</button>
				{/each}
			</div>
		</div>

		<!-- Invoices List -->
		{#if sortedInvoices.length > 0}
			<div class="space-y-3">
				{#each sortedInvoices as invoice (invoice.id)}
					{@const statusBadge = getStatusBadge(invoice.status)}
					<a href="/customer/invoices/{invoice.id}" class="block card-invoice">
						<div class="flex items-center justify-between gap-4">
							<div class="min-w-0 flex-1">
								<div class="mb-1 flex items-center gap-2">
									<span class="text-sm font-medium text-theme">
										Invoice - {formatDate(invoice.date)}
									</span>
								</div>
								{#if hasMultipleCustomers && invoice.customerId}
									<p class="text-sm text-theme-secondary">
										{getCustomerName(invoice.customerId)}
									</p>
								{/if}
								{#if invoice.datePaid}
									<p class="text-xs text-theme-muted">
										Paid on {formatDate(invoice.datePaid)}
									</p>
								{/if}
							</div>
							<div class="flex shrink-0 items-center gap-2">
								<span class="rounded px-2 py-1 text-xs {statusBadge.classes}">
									{statusBadge.text}
								</span>
								<svg
									class="h-5 w-5 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}
			<div class="rounded-xl border border-theme bg-theme-card p-8 text-center">
				<svg
					class="mx-auto mb-4 h-16 w-16 text-theme-muted"
					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="mb-2 text-lg font-semibold text-theme">No Invoices</h2>
				<p class="mx-auto max-w-md text-theme-muted">
					{#if activeFilter === 'sent'}
						No pending invoices.
					{:else if activeFilter === 'paid'}
						No paid invoices yet.
					{:else}
						No invoices found.
					{/if}
				</p>
			</div>
		{/if}
	</ContentContainer>
</div>
