<script lang="ts">
	import ContentContainer from '$lib/components/layout/ContentContainer.svelte';
	import AdminPageHeader from '$lib/components/admin/AdminPageHeader.svelte';
	import DeleteConfirmModal from '$lib/components/admin/DeleteConfirmModal.svelte';
	import InvoiceForm from '$lib/components/admin/invoices/InvoiceForm.svelte';
	import AddRevenuesModal from '$lib/components/admin/invoices/AddRevenuesModal.svelte';
	import AddProjectsModal from '$lib/components/admin/invoices/AddProjectsModal.svelte';
	import InvoiceTabs from '$lib/components/admin/invoices/InvoiceTabs.svelte';
	import WaveValidationSection from '$lib/components/admin/invoices/wave/WaveValidationSection.svelte';
	import WaveLinkProductModal from '$lib/components/admin/invoices/wave/WaveLinkProductModal.svelte';
	import WaveInvoiceForm from '$lib/components/admin/invoices/wave/WaveInvoiceForm.svelte';
	import WaveInvoiceEditForm from '$lib/components/admin/invoices/wave/WaveInvoiceEditForm.svelte';
	import WaveInvoicePreview from '$lib/components/admin/invoices/wave/WaveInvoicePreview.svelte';
	import WaveCustomerLinkForm from '$lib/components/admin/customers/WaveCustomerLinkForm.svelte';
	import { DeleteInvoiceStore, UpdateInvoiceStore } from '$houdini';
	import { enhance } from '$app/forms';
	import { goto, invalidateAll } from '$app/navigation';
	import { offCanvas } from '$lib/stores/offCanvas.svelte';
	import { fromGlobalId } from '$lib/utils/relay';
	import type { PageData } from './$types';
	import type { InvoiceTab } from '$lib/components/admin/invoices/wave/types';

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

	let invoice = $derived(data.invoice);
	let customers = $derived(data.customers?.data?.customers ?? []);
	let customerLookup = $derived(data.customerLookup);
	let accounts = $derived(data.accounts?.data?.accounts ?? []);
	let accountLookup = $derived(data.accountLookup);
	let waveCustomers = $derived(data.waveCustomers);
	let waveProducts = $derived(data.waveProducts);
	let waveInvoice = $derived(data.waveInvoice);

	// Tab state
	let activeTab = $state<InvoiceTab>('details');

	// Get customer name from UUID
	let customerName = $derived(
		customerLookup.get(invoice.customerId)?.customerName ?? 'Unknown Customer'
	);

	let showDeleteModal = $state(false);
	let showAddRevenuesModal = $state(false);
	let showAddProjectsModal = $state(false);
	let isDeleting = $state(false);
	let isUpdatingStatus = $state(false);

	// Wave integration state
	let showLinkProductModal = $state(false);
	let linkingEntity = $state<{
		type: 'revenue' | 'project';
		id: string;
		description: string;
		currentWaveServiceId: string | null;
	} | null>(null);
	let showWaveInvoiceForm = $state(false);
	let isEditingWaveInvoice = $state(false);
	let isSendingWaveInvoice = $state(false);
	let isApprovingWaveInvoice = $state(false);
	let isRefreshingWaveInvoice = $state(false);
	let isDeletingWaveInvoice = $state(false);
	let approveWaveInvoiceFormRef = $state<HTMLFormElement | null>(null);
	let deleteWaveInvoiceFormRef = $state<HTMLFormElement | null>(null);

	// Wave validation derived state
	let customerData = $derived(() => {
		const customer = customers.find((c) => fromGlobalId(c.id) === invoice.customerId);
		return {
			customerName: customer?.name ?? 'Unknown Customer',
			waveCustomerId: customer?.waveCustomerId ?? null
		};
	});

	let unlinkedRevenues = $derived(invoice.revenues.filter((r) => !r.waveServiceId));
	let unlinkedProjects = $derived(invoice.projects.filter((p) => !p.waveServiceId));
	let validationErrors = $derived(
		(customerData().waveCustomerId ? 0 : 1) + unlinkedRevenues.length + unlinkedProjects.length
	);
	let hasWaveInvoice = $derived(!!invoice.waveInvoiceId && !!waveInvoice);

	const deleteStore = new DeleteInvoiceStore();
	const updateStore = new UpdateInvoiceStore();

	// Calculate totals
	let revenuesTotal = $derived(
		invoice.revenues.reduce((sum, r) => sum + parseFloat(String(r.amount ?? 0)), 0)
	);

	let projectsTotal = $derived(
		invoice.projects.reduce((sum, p) => sum + parseFloat(String(p.amount ?? 0)), 0)
	);

	let invoiceTotal = $derived(revenuesTotal + projectsTotal);

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

	function formatShortDate(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 | number | null | undefined): string {
		if (value === null || value === undefined) return '$0.00';
		const num = typeof value === 'string' ? parseFloat(value) : value;
		return new Intl.NumberFormat('en-US', {
			style: 'currency',
			currency: 'USD'
		}).format(num);
	}

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

	// Get status display label
	function getStatusLabel(status: string): string {
		switch (status) {
			case 'DRAFT':
				return 'Draft';
			case 'SENT':
				return 'Sent';
			case 'PAID':
				return 'Paid';
			case 'OVERDUE':
				return 'Overdue';
			case 'CANCELLED':
				return 'Cancelled';
			default:
				return status;
		}
	}

	// Get payment type label
	function getPaymentTypeLabel(paymentType: string | null): string {
		if (!paymentType) return '—';
		switch (paymentType) {
			case 'CHECK':
				return 'Check';
			case 'CREDIT_CARD':
				return 'Credit Card';
			case 'BANK_TRANSFER':
				return 'Bank Transfer';
			case 'CASH':
				return 'Cash';
			default:
				return paymentType;
		}
	}

	// Get account name for a revenue (accountId is UUID, account.id is GlobalID)
	function getAccountNameForRevenue(accountId: string): string {
		const account = accounts.find((a) => fromGlobalId(a.id) === accountId);
		return account?.name ?? 'Unknown Account';
	}

	// Get account name for a project
	function getAccountNameForProject(project: { accountAddressId: string | null }): string {
		if (project.accountAddressId) {
			const accountInfo = accountLookup.get(project.accountAddressId);
			if (accountInfo) {
				return accountInfo.accountName;
			}
		}
		return '';
	}

	// Get project display name
	function getProjectDisplayName(project: {
		name: string;
		date: string;
		accountAddressId: string | null;
	}): string {
		const locationName = getAccountNameForProject(project);

		if (locationName) {
			return `${project.name} - ${locationName}`;
		}
		return project.name;
	}

	// Sorted revenues by account name
	let sortedRevenues = $derived(
		[...invoice.revenues].sort((a, b) => {
			const nameA = getAccountNameForRevenue(a.accountId);
			const nameB = getAccountNameForRevenue(b.accountId);
			return nameA.localeCompare(nameB);
		})
	);

	// Sorted projects by account name
	let sortedProjects = $derived(
		[...invoice.projects].sort((a, b) => {
			const nameA = getAccountNameForProject(a);
			const nameB = getAccountNameForProject(b);
			return nameA.localeCompare(nameB);
		})
	);

	const statusOptions = [
		{ value: 'DRAFT', label: 'Draft' },
		{ value: 'SENT', label: 'Sent' },
		{ value: 'PAID', label: 'Paid' },
		{ value: 'OVERDUE', label: 'Overdue' },
		{ value: 'CANCELLED', label: 'Cancelled' }
	];

	// Quick status update
	async function updateStatus(newStatus: string) {
		if (newStatus === invoice.status) return;
		isUpdatingStatus = true;

		try {
			// If marking as paid and no date_paid, set it to today
			const datePaid =
				newStatus === 'PAID' && !invoice.datePaid
					? new Date().toISOString().split('T')[0]
					: invoice.datePaid;

			await updateStore.mutate({
				input: {
					id: invoice.id,
					status: newStatus,
					datePaid
				}
			});
			await invalidateAll();
		} catch (err) {
			console.error('Failed to update status:', err);
		} finally {
			isUpdatingStatus = false;
		}
	}

	// Remove a revenue from the invoice
	async function removeRevenue(revenueId: string) {
		// IDs are already GlobalIDs from the GraphQL query
		const newRevenueIds = invoice.revenues.map((r) => r.id).filter((id) => id !== revenueId);

		try {
			await updateStore.mutate({
				input: {
					id: invoice.id,
					revenueIds: newRevenueIds
				}
			});
			await invalidateAll();
		} catch (err) {
			console.error('Failed to remove revenue:', err);
		}
	}

	// Remove a project from the invoice
	async function removeProject(projectId: string) {
		// IDs are already GlobalIDs from the GraphQL query
		const newProjectIds = invoice.projects.map((p) => p.id).filter((id) => id !== projectId);

		try {
			await updateStore.mutate({
				input: {
					id: invoice.id,
					projectIds: newProjectIds
				}
			});
			await invalidateAll();
		} catch (err) {
			console.error('Failed to remove project:', err);
		}
	}

	function showEditForm() {
		offCanvas.showRight({
			title: 'Edit Invoice',
			content: editFormContent
		});
	}

	async function handleSuccess() {
		await invalidateAll();
	}

	// Wave integration handlers
	function handleLinkCustomer() {
		const customer = customers.find((c) => fromGlobalId(c.id) === invoice.customerId);
		if (!customer) return;

		offCanvas.showRight({
			title: 'Link Wave Customer',
			content: linkCustomerContent
		});
	}

	function handleLinkRevenue(revenueId: string, accountName: string) {
		const revenue = invoice.revenues.find((r) => r.id === revenueId);
		if (!revenue) return;

		linkingEntity = {
			type: 'revenue',
			id: revenueId,
			description: accountName,
			currentWaveServiceId: revenue.waveServiceId ?? null
		};
		showLinkProductModal = true;
	}

	function handleLinkProject(projectId: string, projectName: string) {
		const project = invoice.projects.find((p) => p.id === projectId);
		if (!project) return;

		linkingEntity = {
			type: 'project',
			id: projectId,
			description: projectName,
			currentWaveServiceId: project.waveServiceId ?? null
		};
		showLinkProductModal = true;
	}

	async function handleLinkProductSuccess() {
		showLinkProductModal = false;
		linkingEntity = null;
		await invalidateAll();
	}

	function handleLinkProductCancel() {
		showLinkProductModal = false;
		linkingEntity = null;
	}

	function handleCreateWaveInvoice() {
		showWaveInvoiceForm = true;
	}

	async function handleWaveInvoiceSuccess() {
		showWaveInvoiceForm = false;
		await invalidateAll();
	}

	function handleWaveInvoiceCancel() {
		showWaveInvoiceForm = false;
	}

	let sendWaveInvoiceFormRef = $state<HTMLFormElement | null>(null);

	function handleSendWaveInvoice() {
		sendWaveInvoiceFormRef?.requestSubmit();
	}

	function handleApproveWaveInvoice() {
		approveWaveInvoiceFormRef?.requestSubmit();
	}

	async function handleRefreshWaveInvoice() {
		isRefreshingWaveInvoice = true;
		await invalidateAll();
		isRefreshingWaveInvoice = false;
	}

	function handleEditWaveInvoice() {
		isEditingWaveInvoice = true;
	}

	async function handleEditWaveInvoiceSuccess() {
		isEditingWaveInvoice = false;
		await invalidateAll();
	}

	function handleEditWaveInvoiceCancel() {
		isEditingWaveInvoice = false;
	}

	function handleDeleteWaveInvoice() {
		if (confirm('Are you sure you want to delete this Wave invoice? This cannot be undone.')) {
			deleteWaveInvoiceFormRef?.requestSubmit();
		}
	}

	async function handleDelete() {
		isDeleting = true;
		try {
			await deleteStore.mutate({ id: invoice.id });
			await goto('/admin/invoices', { invalidateAll: true });
		} catch (err) {
			console.error('Failed to delete invoice:', err);
			alert('Failed to delete invoice. Please try again.');
		} finally {
			isDeleting = false;
			showDeleteModal = false;
		}
	}
</script>

{#snippet editFormContent()}
	<InvoiceForm {customers} {invoice} onSuccess={handleSuccess} />
{/snippet}

{#snippet linkCustomerContent()}
	{@const customer = customers.find((c) => fromGlobalId(c.id) === invoice.customerId)}
	{#if customer}
		<WaveCustomerLinkForm
			customerId={customer.id}
			currentWaveCustomerId={customer.waveCustomerId}
			{waveCustomers}
			onSuccess={handleSuccess}
		/>
	{/if}
{/snippet}

<svelte:head>
	<title>Invoice - {customerName} - Admin - Nexus</title>
</svelte:head>

<div class="py-8">
	<ContentContainer>
		<AdminPageHeader
			title={customerName}
			subtitle={formatDate(invoice.date)}
			colorScheme="accent6"
			backHref="/admin/invoices"
		/>

		<!-- Status & Actions Card -->
		<div class="mb-6 card-padded">
			<div class="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
				<div class="flex items-center gap-3">
					<span
						class={`inline-flex items-center rounded-full px-3 py-1 text-sm font-medium ${getStatusClasses(invoice.status)}`}
					>
						{getStatusLabel(invoice.status)}
					</span>
					{#if invoice.waveInvoiceId}
						<span class="badge-primary">Linked</span>
					{/if}
				</div>

				<div class="flex items-center gap-3">
					<!-- Quick Status Update -->
					<select
						onchange={(e) => updateStatus(e.currentTarget.value)}
						disabled={isUpdatingStatus}
						class="rounded-lg border border-theme bg-theme px-3 py-2 text-sm text-theme focus:border-primary-500 focus:ring-1 focus:ring-primary-500 disabled:cursor-not-allowed disabled:opacity-50"
					>
						{#each statusOptions as option (option.value)}
							<option value={option.value} selected={option.value === invoice.status}
								>{option.label}</option
							>
						{/each}
					</select>

					<!-- Edit Button -->
					<button
						onclick={showEditForm}
						class="flex items-center gap-2 rounded-lg bg-primary-500 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-primary-600"
					>
						<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="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"
							/>
						</svg>
						Edit
					</button>
				</div>
			</div>
		</div>

		<!-- Tabs -->
		<InvoiceTabs
			{activeTab}
			waveLinked={hasWaveInvoice}
			{validationErrors}
			onTabChange={(tab) => (activeTab = tab)}
		/>

		{#if activeTab === 'details'}
			<!-- Invoice Summary Card -->
			<div class="mb-6 card-padded">
				<h3 class="mb-4 text-sm font-medium text-theme-muted">Invoice Summary</h3>

				<div class="space-y-4">
					<!-- Revenues Total -->
					<div class="flex items-center justify-between border-b border-theme py-3">
						<div class="flex items-center gap-3">
							<div
								class="flex h-10 w-10 items-center justify-center rounded-lg bg-secondary-500/20"
							>
								<svg
									class="h-5 w-5 text-secondary-600 dark:text-secondary-400"
									style="fill: none"
									stroke="currentColor"
									viewBox="0 0 24 24"
								>
									<path
										stroke-linecap="round"
										stroke-linejoin="round"
										stroke-width="2"
										d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
									/>
								</svg>
							</div>
							<div>
								<p class="font-medium text-theme">Revenues</p>
								<p class="text-sm text-theme-muted">
									{invoice.revenues.length} item{invoice.revenues.length !== 1 ? 's' : ''}
								</p>
							</div>
						</div>
						<p class="text-lg font-bold text-secondary-600 dark:text-secondary-400">
							{formatCurrency(revenuesTotal)}
						</p>
					</div>

					<!-- Projects Total -->
					<div class="flex items-center justify-between border-b border-theme py-3">
						<div class="flex items-center gap-3">
							<div class="flex h-10 w-10 items-center justify-center rounded-lg bg-accent-500/20">
								<svg
									class="h-5 w-5 text-accent-600 dark:text-accent-400"
									style="fill: none"
									stroke="currentColor"
									viewBox="0 0 24 24"
								>
									<path
										stroke-linecap="round"
										stroke-linejoin="round"
										stroke-width="2"
										d="M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-6l-2-2H5a2 2 0 00-2 2z"
									/>
								</svg>
							</div>
							<div>
								<p class="font-medium text-theme">Projects</p>
								<p class="text-sm text-theme-muted">
									{invoice.projects.length} item{invoice.projects.length !== 1 ? 's' : ''}
								</p>
							</div>
						</div>
						<p class="text-lg font-bold text-accent-600 dark:text-accent-400">
							{formatCurrency(projectsTotal)}
						</p>
					</div>

					<!-- Invoice Total -->
					<div class="flex items-center justify-between py-3">
						<div class="flex items-center gap-3">
							<div class="flex h-10 w-10 items-center justify-center rounded-lg bg-accent6-500/20">
								<svg
									class="h-5 w-5 text-accent6-600 dark:text-accent6-400"
									style="fill: none"
									stroke="currentColor"
									viewBox="0 0 24 24"
								>
									<path
										stroke-linecap="round"
										stroke-linejoin="round"
										stroke-width="2"
										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>
							</div>
							<div>
								<p class="font-medium text-theme">Invoice Total</p>
								<p class="text-sm text-theme-muted">Combined total</p>
							</div>
						</div>
						<p class="text-xl font-bold text-accent6-600 dark:text-accent6-400">
							{formatCurrency(invoiceTotal)}
						</p>
					</div>
				</div>
			</div>

			<!-- Revenues Section -->
			<div class="mb-6 card-padded">
				<div class="mb-4 flex items-center justify-between">
					<h3 class="text-sm font-medium text-theme-muted">Revenues</h3>
					<button
						onclick={() => (showAddRevenuesModal = true)}
						class="flex items-center gap-1.5 rounded-lg bg-secondary-500/10 px-3 py-1.5 text-sm font-medium text-secondary-600 transition-colors hover:bg-secondary-500/20 dark:text-secondary-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="M12 4v16m8-8H4"
							/>
						</svg>
						Add Revenues
					</button>
				</div>

				{#if invoice.revenues.length === 0}
					<p class="text-sm text-theme-muted italic">No revenues added to this invoice.</p>
				{:else}
					<div class="space-y-2">
						{#each sortedRevenues as revenue (revenue.id)}
							<div class="rounded-lg border border-theme bg-theme-secondary p-3">
								<div class="flex items-start justify-between gap-2">
									<div class="min-w-0 flex-1">
										<p class="text-sm font-medium text-theme">
											{getAccountNameForRevenue(revenue.accountId)}
										</p>
										<p class="text-xs text-theme-muted">
											{formatShortDate(revenue.startDate)}
											{#if revenue.endDate}
												- {formatShortDate(revenue.endDate)}
											{:else}
												- Ongoing
											{/if}
										</p>
									</div>
									<div class="flex items-center gap-2">
										{#if revenue.waveServiceId}
											<span class="badge-primary">Linked</span>
										{/if}
										<span class="text-sm font-semibold text-secondary-600 dark:text-secondary-400">
											{formatCurrency(revenue.amount)}
										</span>
										<button
											onclick={() => removeRevenue(revenue.id)}
											class="rounded p-1 text-theme-muted transition-colors hover:bg-error-500/10 hover:text-error-600 dark:hover:text-error-400"
											title="Remove revenue"
										>
											<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="M6 18L18 6M6 6l12 12"
												/>
											</svg>
										</button>
									</div>
								</div>
							</div>
						{/each}
					</div>
				{/if}
			</div>

			<!-- Projects Section -->
			<div class="mb-6 card-padded">
				<div class="mb-4 flex items-center justify-between">
					<h3 class="text-sm font-medium text-theme-muted">Projects</h3>
					<button
						onclick={() => (showAddProjectsModal = true)}
						class="flex items-center gap-1.5 rounded-lg bg-accent-500/10 px-3 py-1.5 text-sm font-medium text-accent-600 transition-colors hover:bg-accent-500/20 dark:text-accent-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="M12 4v16m8-8H4"
							/>
						</svg>
						Add Projects
					</button>
				</div>

				{#if invoice.projects.length === 0}
					<p class="text-sm text-theme-muted italic">No projects added to this invoice.</p>
				{:else}
					<div class="space-y-2">
						{#each sortedProjects as project (project.id)}
							<div class="rounded-lg border border-theme bg-theme-secondary p-3">
								<div class="flex items-start justify-between gap-2">
									<div class="min-w-0 flex-1">
										<p class="text-sm font-medium text-theme">{getProjectDisplayName(project)}</p>
										<p class="text-xs text-theme-muted">{formatShortDate(project.date)}</p>
									</div>
									<div class="flex items-center gap-2">
										{#if project.waveServiceId}
											<span class="badge-primary">Linked</span>
										{/if}
										<span class="text-sm font-semibold text-accent-600 dark:text-accent-400">
											{formatCurrency(project.amount)}
										</span>
										<button
											onclick={() => removeProject(project.id)}
											class="rounded p-1 text-theme-muted transition-colors hover:bg-error-500/10 hover:text-error-600 dark:hover:text-error-400"
											title="Remove project"
										>
											<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="M6 18L18 6M6 6l12 12"
												/>
											</svg>
										</button>
									</div>
								</div>
							</div>
						{/each}
					</div>
				{/if}
			</div>

			<!-- Invoice Details Card -->
			<div class="mb-6 card-padded">
				<h3 class="mb-4 text-sm font-medium text-theme-muted">Invoice Details</h3>

				<div class="space-y-4">
					<!-- Customer -->
					<div class="flex items-center justify-between border-b border-theme py-3">
						<div class="flex items-center gap-3">
							<div class="flex h-10 w-10 items-center justify-center rounded-lg bg-accent6-500/20">
								<svg
									class="h-5 w-5 text-accent6-600 dark:text-accent6-400"
									style="fill: none"
									stroke="currentColor"
									viewBox="0 0 24 24"
								>
									<path
										stroke-linecap="round"
										stroke-linejoin="round"
										stroke-width="2"
										d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"
									/>
								</svg>
							</div>
							<div>
								<p class="text-sm text-theme-muted">Customer</p>
								<p class="font-medium text-theme">{customerName}</p>
							</div>
						</div>
					</div>

					<!-- Invoice Date -->
					<div class="flex items-center justify-between border-b border-theme py-3">
						<div class="flex items-center gap-3">
							<div class="flex h-10 w-10 items-center justify-center rounded-lg bg-primary-500/20">
								<svg
									class="h-5 w-5 text-primary-600 dark:text-primary-400"
									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>
							</div>
							<div>
								<p class="text-sm text-theme-muted">Invoice Date</p>
								<p class="font-medium text-theme">{formatDate(invoice.date)}</p>
							</div>
						</div>
					</div>

					<!-- Payment Info (if paid) -->
					{#if invoice.status === 'PAID'}
						<div class="flex items-center justify-between border-b border-theme py-3">
							<div class="flex items-center gap-3">
								<div
									class="flex h-10 w-10 items-center justify-center rounded-lg bg-success-500/20"
								>
									<svg
										class="h-5 w-5 text-success-600 dark:text-success-400"
										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>
								</div>
								<div>
									<p class="text-sm text-theme-muted">Date Paid</p>
									<p class="font-medium text-success-600 dark:text-success-400">
										{formatDate(invoice.datePaid)}
									</p>
								</div>
							</div>
						</div>

						<div class="flex items-center justify-between py-3">
							<div class="flex items-center gap-3">
								<div
									class="flex h-10 w-10 items-center justify-center rounded-lg bg-secondary-500/20"
								>
									<svg
										class="h-5 w-5 text-secondary-600 dark:text-secondary-400"
										style="fill: none"
										stroke="currentColor"
										viewBox="0 0 24 24"
									>
										<path
											stroke-linecap="round"
											stroke-linejoin="round"
											stroke-width="2"
											d="M3 10h18M7 15h1m4 0h1m-7 4h12a3 3 0 003-3V8a3 3 0 00-3-3H6a3 3 0 00-3 3v8a3 3 0 003 3z"
										/>
									</svg>
								</div>
								<div>
									<p class="text-sm text-theme-muted">Payment Method</p>
									<p class="font-medium text-theme">{getPaymentTypeLabel(invoice.paymentType)}</p>
								</div>
							</div>
						</div>
					{/if}
				</div>
			</div>

			<!-- Danger Zone -->
			<div class="danger-zone">
				<h2 class="danger-zone-title">Danger Zone</h2>
				<p class="danger-zone-text">
					Deleting this invoice will permanently remove it. This action cannot be undone.
				</p>
				<button onclick={() => (showDeleteModal = true)} class="btn-danger">
					Delete Invoice
				</button>
			</div>
		{:else if activeTab === 'wave'}
			<!-- Wave Tab Content -->
			{#if hasWaveInvoice && waveInvoice}
				<!-- Hidden form for approving Wave invoice -->
				<form
					bind:this={approveWaveInvoiceFormRef}
					method="POST"
					action="?/approveWaveInvoice"
					use:enhance={() => {
						isApprovingWaveInvoice = true;
						return async ({ result }) => {
							isApprovingWaveInvoice = false;
							if (result.type === 'failure') {
								const errorMsg = result.data?.error;
								alert(typeof errorMsg === 'string' ? errorMsg : 'Failed to approve invoice');
							} else if (result.type === 'success') {
								await invalidateAll();
							}
						};
					}}
					class="hidden"
				>
					<input type="hidden" name="invoiceId" value={waveInvoice.id} />
				</form>

				<!-- Hidden form for sending Wave invoice -->
				<form
					bind:this={sendWaveInvoiceFormRef}
					method="POST"
					action="?/sendWaveInvoice"
					use:enhance={() => {
						isSendingWaveInvoice = true;
						return async ({ result }) => {
							isSendingWaveInvoice = false;
							if (result.type === 'failure') {
								const errorMsg = result.data?.error;
								alert(typeof errorMsg === 'string' ? errorMsg : 'Failed to send invoice');
							} else if (result.type === 'success') {
								await invalidateAll();
							}
						};
					}}
					class="hidden"
				>
					<input type="hidden" name="invoiceId" value={waveInvoice.id} />
					<input type="hidden" name="nexusInvoiceId" value={invoice.id} />
					<input type="hidden" name="customerEmail" value={waveInvoice.customer.email ?? ''} />
				</form>

				<!-- Hidden form for deleting Wave invoice -->
				<form
					bind:this={deleteWaveInvoiceFormRef}
					method="POST"
					action="?/deleteWaveInvoice"
					use:enhance={() => {
						isDeletingWaveInvoice = true;
						return async ({ result }) => {
							isDeletingWaveInvoice = false;
							if (result.type === 'failure') {
								const errorMsg = result.data?.error;
								alert(typeof errorMsg === 'string' ? errorMsg : 'Failed to delete invoice');
							} else if (result.type === 'success') {
								await invalidateAll();
							}
						};
					}}
					class="hidden"
				>
					<input type="hidden" name="waveInvoiceId" value={waveInvoice.id} />
					<input type="hidden" name="nexusInvoiceId" value={invoice.id} />
				</form>

				{#if isEditingWaveInvoice}
					<!-- Wave Invoice Edit Form -->
					<WaveInvoiceEditForm
						{waveInvoice}
						{waveProducts}
						onSuccess={handleEditWaveInvoiceSuccess}
						onCancel={handleEditWaveInvoiceCancel}
					/>
				{:else}
					<!-- Wave Invoice Preview -->
					<WaveInvoicePreview
						{waveInvoice}
						onSend={handleSendWaveInvoice}
						onApprove={handleApproveWaveInvoice}
						onRefresh={handleRefreshWaveInvoice}
						onEdit={handleEditWaveInvoice}
						onDelete={handleDeleteWaveInvoice}
						isSending={isSendingWaveInvoice}
						isApproving={isApprovingWaveInvoice}
						isRefreshing={isRefreshingWaveInvoice}
						isDeleting={isDeletingWaveInvoice}
					/>
				{/if}
			{:else if showWaveInvoiceForm}
				<!-- Wave Invoice Creation Form -->
				<WaveInvoiceForm
					{invoice}
					waveCustomerId={customerData().waveCustomerId ?? ''}
					revenues={invoice.revenues}
					projects={invoice.projects}
					{waveProducts}
					onSuccess={handleWaveInvoiceSuccess}
					onCancel={handleWaveInvoiceCancel}
				/>
			{:else}
				<!-- Wave Validation Section -->
				<WaveValidationSection
					customer={customerData()}
					revenues={invoice.revenues}
					projects={invoice.projects}
					{waveProducts}
					{accounts}
					onLinkCustomer={handleLinkCustomer}
					onLinkRevenue={handleLinkRevenue}
					onLinkProject={handleLinkProject}
					onCreateInvoice={handleCreateWaveInvoice}
				/>
			{/if}
		{/if}
	</ContentContainer>
</div>

<DeleteConfirmModal
	bind:open={showDeleteModal}
	title="Delete Invoice"
	message="Are you sure you want to delete this invoice? This action cannot be undone."
	onconfirm={handleDelete}
	oncancel={() => {}}
	loading={isDeleting}
/>

<AddRevenuesModal bind:open={showAddRevenuesModal} {invoice} {accounts} onSuccess={handleSuccess} />

<AddProjectsModal
	bind:open={showAddProjectsModal}
	{invoice}
	{accountLookup}
	onSuccess={handleSuccess}
/>

<!-- Wave Link Product Modal -->
{#if linkingEntity}
	<WaveLinkProductModal
		open={showLinkProductModal}
		entityType={linkingEntity.type}
		entityId={linkingEntity.id}
		entityDescription={linkingEntity.description}
		currentWaveServiceId={linkingEntity.currentWaveServiceId}
		{waveProducts}
		onSuccess={handleLinkProductSuccess}
		onCancel={handleLinkProductCancel}
	/>
{/if}
