<script lang="ts">
	import ContentContainer from '$lib/components/layout/ContentContainer.svelte';
	import DeleteConfirmModal from '$lib/components/admin/DeleteConfirmModal.svelte';
	import WaveTabs, { type WaveTab } from '$lib/components/admin/invoices/wave/WaveTabs.svelte';
	import WaveProductsTab from '$lib/components/admin/invoices/wave/WaveProductsTab.svelte';
	import WaveCustomersTab from '$lib/components/admin/invoices/wave/WaveCustomersTab.svelte';
	import type { WaveProduct, WaveCustomer } from '$lib/components/admin/invoices/wave/types';
	import { SvelteDate } from 'svelte/reactivity';
	import { enhance } from '$app/forms';
	import type { PageData } from './$types';

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

	let invoices = $derived(data.invoices);
	let products = $derived(data.products as WaveProduct[]);
	let archivedProducts = $derived(data.archivedProducts as WaveProduct[]);
	let customers = $derived(data.customers as WaveCustomer[]);
	let incomeAccounts = $derived(data.incomeAccounts);
	let invoicePageInfo = $derived(data.invoicePageInfo);

	// Tab state
	let activeTab = $state<WaveTab>('invoices');

	// Delete modal state
	let showDeleteModal = $state(false);
	let deleteType = $state<'product' | 'customer'>('product');
	let deleteItem = $state<WaveProduct | WaveCustomer | null>(null);
	let deleteFormRef = $state<HTMLFormElement | null>(null);
	let isDeleting = $state(false);

	// Invoice filters (existing functionality)
	let searchQuery = $state('');
	let selectedStatus = $state<string>('');

	let filteredInvoices = $derived.by(() => {
		let filtered = invoices;
		if (selectedStatus) {
			filtered = filtered.filter((i) => i.status === selectedStatus);
		}
		if (searchQuery.trim()) {
			const query = searchQuery.toLowerCase();
			filtered = filtered.filter((i) => {
				const customerName = i.customer.name.toLowerCase();
				const invoiceNumber = i.invoiceNumber.toLowerCase();
				return customerName.includes(query) || invoiceNumber.includes(query);
			});
		}
		return filtered;
	});

	function formatDate(dateStr: string | null): string {
		if (!dateStr) return '—';
		return new Date(dateStr + 'T00:00:00').toLocaleDateString('en-US', {
			month: 'short',
			day: 'numeric',
			year: 'numeric'
		});
	}

	function formatCurrency(value: string, symbol: string): string {
		const num = parseFloat(value.replace(/,/g, ''));
		return `${symbol}${num.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
	}

	function getStatusClasses(status: string): string {
		switch (status) {
			case 'DRAFT':
			case 'SAVED':
				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 'VIEWED':
				return 'bg-accent2-500/10 text-accent2-600 dark:text-accent2-400';
			case 'PAID':
				return 'bg-success-500/10 text-success-600 dark:text-success-400';
			case 'PARTIAL':
				return 'bg-warning-500/10 text-warning-600 dark:text-warning-400';
			case 'OVERDUE':
				return 'bg-error-500/10 text-error-600 dark:text-error-400';
			default:
				return 'bg-gray-500/10 text-gray-600 dark:text-gray-400';
		}
	}

	function getStatusLabel(status: string): string {
		switch (status) {
			case 'DRAFT':
				return 'Draft';
			case 'SAVED':
				return 'Saved';
			case 'SENT':
				return 'Sent';
			case 'VIEWED':
				return 'Viewed';
			case 'PAID':
				return 'Paid';
			case 'PARTIAL':
				return 'Partial';
			case 'OVERDUE':
				return 'Overdue';
			default:
				return status;
		}
	}

	function isOverdue(dueDate: string, status: string): boolean {
		if (status === 'PAID') return false;
		const due = new Date(dueDate + 'T00:00:00');
		const today = new SvelteDate();
		today.setHours(0, 0, 0, 0);
		return due < today;
	}

	function handleArchiveProduct(product: WaveProduct) {
		deleteType = 'product';
		deleteItem = product;
		showDeleteModal = true;
	}

	function handleDeleteCustomer(customer: WaveCustomer) {
		deleteType = 'customer';
		deleteItem = customer;
		showDeleteModal = true;
	}

	async function handleConfirmDelete() {
		if (!deleteItem) return;
		deleteFormRef?.requestSubmit();
	}

	function handleCancelDelete() {
		showDeleteModal = false;
		deleteItem = null;
	}

	// Computed values for delete modal
	let deleteTitle = $derived(deleteType === 'product' ? 'Archive Product' : 'Delete Customer');
	let deleteMessage = $derived.by(() => {
		const name = deleteItem?.name ?? '';
		if (deleteType === 'product') {
			return `Are you sure you want to archive "${name}"? This will hide it from the active products list.`;
		}
		return `Are you sure you want to delete "${name}"? This action cannot be undone.`;
	});
	let deleteConfirmLabel = $derived(deleteType === 'product' ? 'Archive' : 'Delete');
</script>

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

<!-- Hidden forms for delete actions -->
<form
	bind:this={deleteFormRef}
	method="POST"
	action={deleteType === 'product' ? '?/archiveProduct' : '?/deleteCustomer'}
	use:enhance={() => {
		isDeleting = true;
		return async ({ result, update }) => {
			isDeleting = false;
			if (result.type === 'success') {
				showDeleteModal = false;
				deleteItem = null;
				await update({ reset: false });
			} else if (result.type === 'failure') {
				showDeleteModal = false;
				deleteItem = null;
			}
		};
	}}
	class="hidden"
>
	<input type="hidden" name="id" value={deleteItem?.id ?? ''} />
</form>

<!-- Delete Confirmation Modal -->
<DeleteConfirmModal
	bind:open={showDeleteModal}
	title={deleteTitle}
	message={deleteMessage}
	confirmLabel={deleteConfirmLabel}
	loading={isDeleting}
	onconfirm={handleConfirmDelete}
	oncancel={handleCancelDelete}
/>

<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/invoices"
						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">
							Wave
						</h1>
						<p class="mt-2 text-theme-secondary">
							{#if data.businessName}
								Managing <span class="font-medium">{data.businessName}</span>
							{:else}
								Manage your Wave accounting data
							{/if}
						</p>
					</div>
				</div>
			</div>
		</div>

		<!-- Error State -->
		{#if data.error}
			<div class="mb-6 danger-zone">
				<div class="flex items-start gap-3">
					<svg
						class="h-5 w-5 flex-shrink-0 text-error-500"
						style="fill: none"
						stroke="currentColor"
						viewBox="0 0 24 24"
					>
						<path
							stroke-linecap="round"
							stroke-linejoin="round"
							stroke-width="2"
							d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"
						/>
					</svg>
					<div>
						<h3 class="font-medium text-error-700 dark:text-error-400">Failed to load Wave data</h3>
						<p class="mt-1 text-sm text-error-600 dark:text-error-300">{data.error}</p>
					</div>
				</div>
			</div>
		{/if}

		<!-- Tabs -->
		<WaveTabs
			{activeTab}
			invoiceCount={invoicePageInfo.totalCount}
			productCount={products.length}
			customerCount={customers.length}
			onTabChange={(tab) => (activeTab = tab)}
		/>

		<!-- Tab Content -->
		{#if activeTab === 'invoices'}
			<!-- Search and Filter -->
			{#if invoices.length > 0 || searchQuery || selectedStatus}
				<div class="mb-6 flex flex-col gap-4 sm:flex-row">
					<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 by customer or invoice #..."
							class="placeholder-theme-muted w-full rounded-lg border border-theme bg-theme-card py-2 pr-4 pl-10 text-theme focus:border-accent6-500 focus:ring-1 focus:ring-accent6-500"
						/>
					</div>

					<select
						bind:value={selectedStatus}
						class="rounded-lg border border-theme bg-theme-card px-3 py-2 text-theme focus:border-accent6-500 focus:ring-1 focus:ring-accent6-500 sm:w-40"
					>
						<option value="">All Statuses</option>
						<option value="DRAFT">Draft</option>
						<option value="SAVED">Saved</option>
						<option value="SENT">Sent</option>
						<option value="VIEWED">Viewed</option>
						<option value="PARTIAL">Partial</option>
						<option value="PAID">Paid</option>
						<option value="OVERDUE">Overdue</option>
					</select>
				</div>
			{/if}

			<!-- Invoices List -->
			{#if filteredInvoices.length > 0}
				<div class="space-y-4">
					{#each filteredInvoices as invoice (invoice.id)}
						{@const overdue = isOverdue(invoice.dueDate, invoice.status)}
						<a href="/admin/invoices/wave/{invoice.id}" class="block card-invoice">
							<div class="flex items-start justify-between gap-4">
								<div class="min-w-0 flex-1 space-y-2">
									<div class="flex flex-wrap items-center gap-3">
										<h3 class="text-lg font-semibold text-accent6-600 dark:text-accent6-400">
											{invoice.customer.name}
										</h3>
										<span
											class={`inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium ${overdue && invoice.status !== 'PAID' ? 'bg-error-500/10 text-error-600 dark:text-error-400' : getStatusClasses(invoice.status)}`}
										>
											{overdue && invoice.status !== 'PAID'
												? 'Overdue'
												: getStatusLabel(invoice.status)}
										</span>
									</div>

									<div class="flex flex-wrap items-center gap-4 text-sm text-theme-secondary">
										<span class="font-medium">#{invoice.invoiceNumber}</span>

										<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.invoiceDate)}
										</span>

										{#if invoice.dueDate}
											<span
												class="flex items-center gap-1.5"
												class:text-error-600={overdue && invoice.status !== 'PAID'}
												class:dark:text-error-400={overdue && invoice.status !== 'PAID'}
											>
												<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="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"
													/>
												</svg>
												Due {formatDate(invoice.dueDate)}
											</span>
										{/if}

										{#if invoice.status === 'PAID'}
											<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
											</span>
										{/if}

										{#if invoice.lastViewedAt}
											<span
												class="flex items-center gap-1.5 text-accent2-600 dark:text-accent2-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="M15 12a3 3 0 11-6 0 3 3 0 016 0z"
													/>
													<path
														stroke-linecap="round"
														stroke-linejoin="round"
														stroke-width="2"
														d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"
													/>
												</svg>
												Viewed
											</span>
										{/if}
									</div>
								</div>

								<div class="flex-shrink-0 text-right">
									<div class="text-lg font-semibold text-theme">
										{formatCurrency(invoice.total.value, invoice.total.currency.symbol)}
									</div>
									{#if parseFloat(invoice.amountDue.value) > 0 && invoice.status !== 'PAID'}
										<div class="text-sm text-theme-secondary">
											{formatCurrency(invoice.amountDue.value, invoice.amountDue.currency.symbol)} due
										</div>
									{/if}
								</div>
							</div>
						</a>
					{/each}
				</div>

				<!-- Pagination -->
				{#if invoicePageInfo.totalPages > 1}
					<div class="mt-8 flex items-center justify-center gap-2">
						{#if invoicePageInfo.currentPage > 1}
							<a
								href="?page={invoicePageInfo.currentPage - 1}"
								class="rounded-lg border border-theme interactive bg-theme-card px-4 py-2 text-sm font-medium text-theme"
							>
								Previous
							</a>
						{/if}

						<span class="px-4 text-sm text-theme-secondary">
							Page {invoicePageInfo.currentPage} of {invoicePageInfo.totalPages}
						</span>

						{#if invoicePageInfo.currentPage < invoicePageInfo.totalPages}
							<a
								href="?page={invoicePageInfo.currentPage + 1}"
								class="rounded-lg border border-theme interactive bg-theme-card px-4 py-2 text-sm font-medium text-theme"
							>
								Next
							</a>
						{/if}
					</div>
				{/if}
			{:else if searchQuery || selectedStatus}
				<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 if !data.error}
				<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 Wave Invoices</h2>
					<p class="empty-state-text">
						There are no invoices in your Wave account yet. Create invoices in Wave to see them
						here.
					</p>
				</div>
			{/if}
		{:else if activeTab === 'products'}
			<WaveProductsTab
				{products}
				{archivedProducts}
				{incomeAccounts}
				onArchive={handleArchiveProduct}
			/>
		{:else if activeTab === 'customers'}
			<WaveCustomersTab {customers} onDelete={handleDeleteCustomer} />
		{/if}
	</ContentContainer>
</div>
