<script lang="ts">
	import { invalidateAll } from '$app/navigation';
	import { client } from '$lib/graphql/client';
	import { ContentContainer } from '$lib/components/layout';
	import { AdminDashboardHeader } from '$lib/components/admin';
	import type { WaveInvoice } from '$lib/graphql/queries/wave';
	import {
		APPROVE_WAVE_INVOICE,
		SEND_WAVE_INVOICE,
		DELETE_WAVE_INVOICE
	} from '$lib/graphql/mutations/wave';

	interface PageData {
		invoice: WaveInvoice;
	}

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

	let invoice = $derived(data.invoice);

	// Loading states
	let actionLoading = $state<string | null>(null);
	let actionError = $state<string | null>(null);

	// Status badge colors
	function getStatusColor(status: string): string {
		switch (status) {
			case 'DRAFT':
				return 'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-300';
			case 'SAVED':
				return 'bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-400';
			case 'SENT':
				return 'bg-indigo-100 text-indigo-800 dark:bg-indigo-900/30 dark:text-indigo-400';
			case 'VIEWED':
				return 'bg-purple-100 text-purple-800 dark:bg-purple-900/30 dark:text-purple-400';
			case 'PAID':
				return 'bg-success-100 text-success-800 dark:bg-success-900/30 dark:text-success-400';
			case 'PARTIAL':
				return 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-400';
			case 'OVERDUE':
				return 'bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400';
			default:
				return 'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-300';
		}
	}

	// Format currency (strip commas since Wave returns values like "1,600.00")
	function formatMoney(value: string, symbol: string): string {
		const num = parseFloat(value.replace(/,/g, ''));
		return `${symbol}${num.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
	}

	// Format number for line items
	function formatLineAmount(value: number): string {
		return `$${value.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
	}

	// Format date
	function formatDate(dateStr: string): string {
		return new Date(dateStr).toLocaleDateString('en-US', {
			year: 'numeric',
			month: 'short',
			day: 'numeric'
		});
	}

	// Invoice actions
	async function approveInvoice() {
		if (
			!confirm(
				'Are you sure you want to approve this invoice?\n\nThis is a point of no return - the invoice cannot be edited after approval.'
			)
		) {
			return;
		}

		actionLoading = 'approve';
		actionError = null;

		try {
			const result = await client.mutate<{
				approveWaveInvoice: { success: boolean; error?: string };
			}>({
				mutation: APPROVE_WAVE_INVOICE,
				variables: { invoiceId: invoice.id }
			});

			if (result.data?.approveWaveInvoice.success) {
				await invalidateAll();
			} else {
				actionError = result.data?.approveWaveInvoice.error || 'Failed to approve invoice';
			}
		} catch (err) {
			actionError = err instanceof Error ? err.message : 'Failed to approve invoice';
		} finally {
			actionLoading = null;
		}
	}

	async function sendInvoice() {
		if (
			!confirm(
				`Are you sure you want to send invoice #${invoice.invoiceNumber} to ${invoice.customer.name}?\n\nThis will email the invoice to the customer.`
			)
		) {
			return;
		}

		actionLoading = 'send';
		actionError = null;

		try {
			const result = await client.mutate<{ sendWaveInvoice: { success: boolean; error?: string } }>(
				{
					mutation: SEND_WAVE_INVOICE,
					variables: { invoiceId: invoice.id }
				}
			);

			if (result.data?.sendWaveInvoice.success) {
				await invalidateAll();
			} else {
				actionError = result.data?.sendWaveInvoice.error || 'Failed to send invoice';
			}
		} catch (err) {
			actionError = err instanceof Error ? err.message : 'Failed to send invoice';
		} finally {
			actionLoading = null;
		}
	}

	async function deleteInvoice() {
		if (!confirm(`Are you sure you want to delete draft invoice #${invoice.invoiceNumber}?`)) {
			return;
		}

		actionLoading = 'delete';
		actionError = null;

		try {
			const result = await client.mutate<{
				deleteWaveInvoice: { success: boolean; error?: string };
			}>({
				mutation: DELETE_WAVE_INVOICE,
				variables: { invoiceId: invoice.id }
			});

			if (result.data?.deleteWaveInvoice.success) {
				// Redirect back to list after delete
				window.location.href = '/admin/invoices/wave';
			} else {
				actionError = result.data?.deleteWaveInvoice.error || 'Failed to delete invoice';
			}
		} catch (err) {
			actionError = err instanceof Error ? err.message : 'Failed to delete invoice';
		} finally {
			actionLoading = null;
		}
	}
</script>

<svelte:head>
	<title>Invoice #{invoice.invoiceNumber} | Wave | Nexus</title>
</svelte:head>

<!-- Add bottom padding on mobile to account for sticky action bar -->
<div
	class="py-6 sm:py-8 {invoice.status === 'DRAFT' || invoice.status === 'SAVED'
		? 'pb-24 sm:pb-8'
		: ''}"
>
	<ContentContainer>
		<!-- Header -->
		<AdminDashboardHeader
			title="Invoice #{invoice.invoiceNumber}"
			subtitle={invoice.customer.name}
			backHref="/admin/invoices/wave"
		>
			{#snippet actions()}
				{#if invoice.pdfUrl}
					<a
						href={invoice.pdfUrl}
						target="_blank"
						rel="noopener noreferrer"
						class="btn-secondary flex w-full items-center justify-center gap-2 sm:w-auto sm:justify-start"
					>
						<svg class="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
							<path
								stroke-linecap="round"
								stroke-linejoin="round"
								stroke-width="2"
								d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 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>
						<span class="hidden sm:inline">Download PDF</span>
						<span class="sm:hidden">PDF</span>
					</a>
				{/if}
			{/snippet}
		</AdminDashboardHeader>

		<!-- Error display -->
		{#if actionError}
			<div class="mb-4 rounded-lg bg-red-50 p-3 sm:mb-6 sm:p-4 dark:bg-red-900/20">
				<div class="flex">
					<svg class="h-5 w-5 shrink-0 text-red-400" viewBox="0 0 20 20" fill="currentColor">
						<path
							fill-rule="evenodd"
							d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z"
							clip-rule="evenodd"
						/>
					</svg>
					<div class="ml-3 flex-1">
						<p class="text-sm font-medium text-red-800 dark:text-red-200">{actionError}</p>
					</div>
					<button
						type="button"
						class="ml-3 shrink-0 text-red-400 hover:text-red-500"
						onclick={() => {
							actionError = null;
						}}
						aria-label="Dismiss error"
					>
						<svg class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
							<path
								fill-rule="evenodd"
								d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z"
								clip-rule="evenodd"
							/>
						</svg>
					</button>
				</div>
			</div>
		{/if}

		<!-- Mobile: Summary card first (most important info) -->
		<div class="mb-4 lg:hidden">
			<div class="card-invoice">
				<div class="flex items-center justify-between">
					<div>
						<span class="text-sm text-theme-secondary">Total</span>
						<p class="text-2xl font-bold text-accent6-600 dark:text-accent6-400">
							{formatMoney(invoice.total.value, invoice.total.currencySymbol)}
						</p>
					</div>
					<div class="text-right">
						<span
							class="rounded-full px-3 py-1 text-sm font-semibold {getStatusColor(invoice.status)}"
						>
							{invoice.status}
						</span>
						{#if parseFloat(invoice.amountDue.value.replace(/,/g, '')) > 0}
							<p class="mt-1 text-sm">
								<span class="text-theme-muted">Due:</span>
								<span class="font-medium text-red-600 dark:text-red-400">
									{formatMoney(invoice.amountDue.value, invoice.amountDue.currencySymbol)}
								</span>
							</p>
						{:else}
							<p class="mt-1 text-sm font-medium text-success-600 dark:text-success-400">
								Paid in full
							</p>
						{/if}
					</div>
				</div>
				<div
					class="border-theme-border mt-3 flex flex-wrap gap-x-4 gap-y-1 border-t pt-3 text-sm text-theme-secondary"
				>
					<span>Issued: {formatDate(invoice.invoiceDate)}</span>
					{#if invoice.dueDate}
						<span>Due: {formatDate(invoice.dueDate)}</span>
					{/if}
				</div>
			</div>
		</div>

		<div class="grid gap-4 sm:gap-6 lg:grid-cols-3">
			<!-- Main Content -->
			<div class="space-y-4 sm:space-y-6 lg:col-span-2">
				<!-- Invoice Header Card - Desktop only (mobile shows summary above) -->
				<div class="hidden card-invoice lg:block">
					<div class="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
						<div>
							<div class="flex items-center gap-3">
								<h2 class="text-xl font-bold text-theme">Invoice #{invoice.invoiceNumber}</h2>
								<span
									class="rounded-full px-3 py-1 text-sm font-semibold {getStatusColor(
										invoice.status
									)}"
								>
									{invoice.status}
								</span>
							</div>
							<p class="mt-1 text-theme-secondary">{invoice.customer.name}</p>
						</div>
						<div class="text-sm text-theme-secondary sm:text-right">
							<p>Issued: {formatDate(invoice.invoiceDate)}</p>
							{#if invoice.dueDate}
								<p>Due: {formatDate(invoice.dueDate)}</p>
							{/if}
						</div>
					</div>
				</div>

				<!-- Customer info - Mobile only -->
				<div class="card-invoice lg:hidden">
					<h3 class="text-sm font-medium text-theme-secondary">Customer</h3>
					<p class="mt-1 font-semibold text-theme">{invoice.customer.name}</p>
				</div>

				<!-- Line Items -->
				<div class="card-invoice">
					<h3 class="mb-3 font-semibold text-theme sm:mb-4">Line Items ({invoice.items.length})</h3>

					{#if invoice.items.length === 0}
						<p class="py-4 text-center text-theme-muted">No line items</p>
					{:else}
						<!-- Desktop table view -->
						<div class="hidden overflow-x-auto sm:block">
							<table class="w-full text-sm">
								<thead>
									<tr
										class="border-theme-border border-b text-left text-xs font-medium text-theme-secondary uppercase"
									>
										<th class="pb-3">Description</th>
										<th class="pb-3 text-right">Qty</th>
										<th class="pb-3 text-right">Unit Price</th>
										<th class="pb-3 text-right">Total</th>
									</tr>
								</thead>
								<tbody class="divide-theme-border divide-y">
									{#each invoice.items as item}
										<tr>
											<td class="py-3 whitespace-pre-wrap text-theme">{item.description}</td>
											<td class="py-3 text-right text-theme-secondary">{item.quantity}</td>
											<td class="py-3 text-right text-theme-secondary"
												>{formatLineAmount(item.unitPrice)}</td
											>
											<td class="py-3 text-right font-medium text-theme"
												>{formatMoney(item.total.value, item.total.currencySymbol)}</td
											>
										</tr>
									{/each}
								</tbody>
							</table>
						</div>

						<!-- Mobile card view -->
						<div class="space-y-3 sm:hidden">
							{#each invoice.items as item}
								<div class="bg-theme-surface rounded-lg p-3">
									<p class="text-sm font-medium whitespace-pre-wrap text-theme">
										{item.description}
									</p>
									<div class="mt-2 flex items-center justify-between text-sm">
										<span class="text-theme-secondary"
											>{item.quantity} × {formatLineAmount(item.unitPrice)}</span
										>
										<span class="font-semibold text-accent6-600 dark:text-accent6-400"
											>{formatMoney(item.total.value, item.total.currencySymbol)}</span
										>
									</div>
								</div>
							{/each}
						</div>

						<!-- Mobile subtotal -->
						<div
							class="border-theme-border mt-4 flex justify-between border-t pt-3 text-sm sm:hidden"
						>
							<span class="text-theme-secondary">Subtotal</span>
							<span class="font-medium text-theme"
								>{formatMoney(invoice.subtotal.value, invoice.subtotal.currencySymbol)}</span
							>
						</div>
					{/if}
				</div>
			</div>

			<!-- Sidebar - Desktop only -->
			<div class="hidden space-y-6 lg:block">
				<!-- Financial Summary -->
				<div class="card-invoice">
					<h3 class="mb-4 font-semibold text-theme">Summary</h3>
					<dl class="space-y-3 text-sm">
						<div class="flex justify-between">
							<dt class="text-theme-secondary">Subtotal</dt>
							<dd class="text-theme">
								{formatMoney(invoice.subtotal.value, invoice.subtotal.currencySymbol)}
							</dd>
						</div>
						<div class="border-theme-border flex justify-between border-t pt-3">
							<dt class="font-semibold text-theme">Total</dt>
							<dd class="text-lg font-bold text-accent6-600 dark:text-accent6-400">
								{formatMoney(invoice.total.value, invoice.total.currencySymbol)}
							</dd>
						</div>
						<div class="border-theme-border flex justify-between border-t pt-3">
							<dt class="text-theme-secondary">Amount Paid</dt>
							<dd class="text-success-600 dark:text-success-400">
								{formatMoney(invoice.amountPaid.value, invoice.amountPaid.currencySymbol)}
							</dd>
						</div>
						<div class="flex justify-between">
							<dt class="font-medium text-theme">Amount Due</dt>
							<dd
								class={parseFloat(invoice.amountDue.value.replace(/,/g, '')) > 0
									? 'font-semibold text-red-600 dark:text-red-400'
									: 'text-success-600 dark:text-success-400'}
							>
								{formatMoney(invoice.amountDue.value, invoice.amountDue.currencySymbol)}
							</dd>
						</div>
					</dl>
				</div>

				<!-- Actions - Desktop -->
				{#if invoice.status === 'DRAFT' || invoice.status === 'SAVED'}
					<div class="card-invoice">
						<h3 class="mb-4 font-semibold text-theme">Actions</h3>
						<div class="space-y-3">
							{#if invoice.status === 'DRAFT'}
								<button
									type="button"
									class="btn-primary flex w-full items-center justify-center gap-2"
									onclick={approveInvoice}
									disabled={actionLoading === 'approve'}
								>
									{#if actionLoading === 'approve'}
										<svg class="h-4 w-4 animate-spin" fill="none" viewBox="0 0 24 24">
											<circle
												class="opacity-25"
												cx="12"
												cy="12"
												r="10"
												stroke="currentColor"
												stroke-width="4"
											></circle>
											<path
												class="opacity-75"
												fill="currentColor"
												d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
											></path>
										</svg>
									{:else}
										<svg class="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
											<path
												stroke-linecap="round"
												stroke-linejoin="round"
												stroke-width="2"
												d="M5 13l4 4L19 7"
											/>
										</svg>
									{/if}
									Approve Invoice
								</button>
								<button
									type="button"
									class="btn-danger flex w-full items-center justify-center gap-2"
									onclick={deleteInvoice}
									disabled={actionLoading === 'delete'}
								>
									{#if actionLoading === 'delete'}
										<svg class="h-4 w-4 animate-spin" fill="none" viewBox="0 0 24 24">
											<circle
												class="opacity-25"
												cx="12"
												cy="12"
												r="10"
												stroke="currentColor"
												stroke-width="4"
											></circle>
											<path
												class="opacity-75"
												fill="currentColor"
												d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
											></path>
										</svg>
									{:else}
										<svg class="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
											<path
												stroke-linecap="round"
												stroke-linejoin="round"
												stroke-width="2"
												d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"
											/>
										</svg>
									{/if}
									Delete Draft
								</button>
							{:else if invoice.status === 'SAVED'}
								<button
									type="button"
									class="btn-primary flex w-full items-center justify-center gap-2"
									onclick={sendInvoice}
									disabled={actionLoading === 'send'}
								>
									{#if actionLoading === 'send'}
										<svg class="h-4 w-4 animate-spin" fill="none" viewBox="0 0 24 24">
											<circle
												class="opacity-25"
												cx="12"
												cy="12"
												r="10"
												stroke="currentColor"
												stroke-width="4"
											></circle>
											<path
												class="opacity-75"
												fill="currentColor"
												d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
											></path>
										</svg>
									{:else}
										<svg class="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
											<path
												stroke-linecap="round"
												stroke-linejoin="round"
												stroke-width="2"
												d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"
											/>
										</svg>
									{/if}
									Send to Customer
								</button>
							{/if}
						</div>
						{#if invoice.status === 'DRAFT'}
							<p class="mt-3 text-xs text-theme-muted">
								Approving the invoice locks it for editing. You can then send it to the customer.
							</p>
						{:else if invoice.status === 'SAVED'}
							<p class="mt-3 text-xs text-theme-muted">
								This will email the invoice to the customer at their registered email address.
							</p>
						{/if}
					</div>
				{/if}

				<!-- Invoice Info -->
				<div class="card-invoice">
					<h3 class="mb-4 font-semibold text-theme">Invoice Details</h3>
					<dl class="space-y-2 text-sm">
						<div class="flex justify-between gap-2">
							<dt class="shrink-0 text-theme-secondary">Invoice ID</dt>
							<dd class="truncate font-mono text-xs text-theme-muted">{invoice.id}</dd>
						</div>
						<div class="flex justify-between">
							<dt class="text-theme-secondary">Currency</dt>
							<dd class="text-theme">{invoice.total.currencyCode}</dd>
						</div>
					</dl>
				</div>
			</div>
		</div>
	</ContentContainer>
</div>

<!-- Mobile Sticky Action Bar -->
{#if invoice.status === 'DRAFT' || invoice.status === 'SAVED'}
	<div
		class="fixed inset-x-0 bottom-0 z-40 border-t border-theme bg-theme-card p-4 shadow-lg lg:hidden"
	>
		<div class="flex gap-3">
			{#if invoice.status === 'DRAFT'}
				<button
					type="button"
					class="btn-danger flex flex-1 items-center justify-center gap-2 py-3"
					onclick={deleteInvoice}
					disabled={actionLoading === 'delete'}
				>
					{#if actionLoading === 'delete'}
						<svg class="h-5 w-5 animate-spin" fill="none" viewBox="0 0 24 24">
							<circle
								class="opacity-25"
								cx="12"
								cy="12"
								r="10"
								stroke="currentColor"
								stroke-width="4"
							></circle>
							<path
								class="opacity-75"
								fill="currentColor"
								d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
							></path>
						</svg>
					{:else}
						<svg class="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
							<path
								stroke-linecap="round"
								stroke-linejoin="round"
								stroke-width="2"
								d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"
							/>
						</svg>
					{/if}
					Delete
				</button>
				<button
					type="button"
					class="btn-primary flex flex-[2] items-center justify-center gap-2 py-3"
					onclick={approveInvoice}
					disabled={actionLoading === 'approve'}
				>
					{#if actionLoading === 'approve'}
						<svg class="h-5 w-5 animate-spin" fill="none" viewBox="0 0 24 24">
							<circle
								class="opacity-25"
								cx="12"
								cy="12"
								r="10"
								stroke="currentColor"
								stroke-width="4"
							></circle>
							<path
								class="opacity-75"
								fill="currentColor"
								d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
							></path>
						</svg>
					{:else}
						<svg class="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
							<path
								stroke-linecap="round"
								stroke-linejoin="round"
								stroke-width="2"
								d="M5 13l4 4L19 7"
							/>
						</svg>
					{/if}
					Approve Invoice
				</button>
			{:else if invoice.status === 'SAVED'}
				<button
					type="button"
					class="btn-primary flex w-full items-center justify-center gap-2 py-3"
					onclick={sendInvoice}
					disabled={actionLoading === 'send'}
				>
					{#if actionLoading === 'send'}
						<svg class="h-5 w-5 animate-spin" fill="none" viewBox="0 0 24 24">
							<circle
								class="opacity-25"
								cx="12"
								cy="12"
								r="10"
								stroke="currentColor"
								stroke-width="4"
							></circle>
							<path
								class="opacity-75"
								fill="currentColor"
								d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
							></path>
						</svg>
					{:else}
						<svg class="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
							<path
								stroke-linecap="round"
								stroke-linejoin="round"
								stroke-width="2"
								d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"
							/>
						</svg>
					{/if}
					Send to Customer
				</button>
			{/if}
		</div>
	</div>
{/if}
