<script lang="ts">
	import IconSpinner from '$lib/components/icons/IconSpinner.svelte';
	import type { WaveInvoice } from './types';

	interface Props {
		waveInvoice: WaveInvoice;
		onSend: () => void;
		onApprove?: () => void;
		onRefresh: () => void;
		onEdit?: () => void;
		onDelete?: () => void;
		isSending?: boolean;
		isApproving?: boolean;
		isRefreshing?: boolean;
		isDeleting?: boolean;
	}

	let {
		waveInvoice,
		onSend,
		onApprove,
		onRefresh,
		onEdit,
		onDelete,
		isSending = false,
		isApproving = false,
		isRefreshing = false,
		isDeleting = false
	}: Props = $props();

	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 formatDateTime(dateStr: string | null): string {
		if (!dateStr) return '—';
		return new Date(dateStr).toLocaleString('en-US', {
			month: 'short',
			day: 'numeric',
			year: 'numeric',
			hour: 'numeric',
			minute: '2-digit'
		});
	}

	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':
				return 'bg-gray-500/10 text-gray-600 dark:text-gray-400';
			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;
		}
	}

	let canApprove = $derived(waveInvoice.status === 'DRAFT');
	let canSend = $derived(waveInvoice.status === 'SAVED');
	let canEdit = $derived(waveInvoice.status === 'DRAFT' || waveInvoice.status === 'SAVED');
	let canDelete = $derived(waveInvoice.status === 'DRAFT' || waveInvoice.status === 'SAVED');
</script>

<div class="space-y-6">
	<!-- Header with Status and Actions -->
	<div class="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">
				<div class="flex h-12 w-12 items-center justify-center rounded-lg bg-accent6-500/20">
					<svg
						class="h-6 w-6 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>
					<div class="flex items-center gap-2">
						<h3 class="text-lg font-semibold text-theme">
							Invoice #{waveInvoice.invoiceNumber}
						</h3>
						<span
							class="inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium {getStatusClasses(
								waveInvoice.status
							)}"
						>
							{getStatusLabel(waveInvoice.status)}
						</span>
					</div>
					<p class="text-sm text-theme-muted">{waveInvoice.customer.name}</p>
				</div>
			</div>

			<div class="flex flex-wrap items-center gap-2">
				<a
					href={waveInvoice.pdfUrl}
					target="_blank"
					rel="noopener noreferrer"
					class="inline-flex items-center gap-1.5 rounded-lg interactive bg-theme px-3 py-2 text-sm font-medium text-theme"
				>
					<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 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>
					Download PDF
				</a>
				{#if canEdit && onEdit}
					<button
						type="button"
						onclick={onEdit}
						class="inline-flex items-center gap-1.5 rounded-lg interactive bg-theme px-3 py-2 text-sm font-medium text-theme"
					>
						<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>
				{/if}
				{#if canApprove && onApprove}
					<button
						type="button"
						onclick={onApprove}
						disabled={isApproving}
						class="inline-flex items-center gap-1.5 rounded-lg bg-success-500 px-3 py-2 text-sm font-medium text-white transition-colors hover:bg-success-600 disabled:cursor-not-allowed disabled:opacity-50"
					>
						{#if isApproving}
							<IconSpinner class="h-4 w-4" />
							<span>Approving...</span>
						{:else}
							<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="M5 13l4 4L19 7"
								/>
							</svg>
							Approve
						{/if}
					</button>
				{/if}
				{#if canSend}
					<button
						type="button"
						onclick={onSend}
						disabled={isSending}
						class="inline-flex items-center gap-1.5 rounded-lg bg-primary-500 px-3 py-2 text-sm font-medium text-white transition-colors hover:bg-primary-600 disabled:cursor-not-allowed disabled:opacity-50"
					>
						{#if isSending}
							<IconSpinner class="h-4 w-4" />
							<span>Sending...</span>
						{:else}
							<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 19l9 2-9-18-9 18 9-2zm0 0v-8"
								/>
							</svg>
							Send Invoice
						{/if}
					</button>
				{/if}
				<button
					type="button"
					onclick={onRefresh}
					disabled={isRefreshing}
					class="inline-flex items-center gap-1.5 rounded-lg bg-theme px-3 py-2 text-sm font-medium text-theme transition-colors hover:bg-black/5 disabled:cursor-not-allowed disabled:opacity-50 dark:hover:bg-white/10"
					aria-label="Refresh"
				>
					{#if isRefreshing}
						<IconSpinner class="h-4 w-4" />
					{:else}
						<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="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"
							/>
						</svg>
					{/if}
				</button>
				{#if canDelete && onDelete}
					<button
						type="button"
						onclick={onDelete}
						disabled={isDeleting}
						class="inline-flex items-center gap-1.5 rounded-lg bg-error-500/10 px-3 py-2 text-sm font-medium text-error-600 transition-colors hover:bg-error-500/20 disabled:cursor-not-allowed disabled:opacity-50 dark:text-error-400"
					>
						{#if isDeleting}
							<IconSpinner class="h-4 w-4" />
							<span>Deleting...</span>
						{:else}
							<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="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>
							Delete
						{/if}
					</button>
				{/if}
			</div>
		</div>
	</div>

	<!-- Invoice Summary -->
	<div class="card-padded">
		<h4 class="mb-4 text-sm font-medium text-theme-muted">Invoice Summary</h4>

		<div class="space-y-3">
			<div class="flex items-center justify-between py-2">
				<span class="text-theme-secondary">Subtotal</span>
				<span class="font-medium text-theme">
					{formatCurrency(waveInvoice.subtotal.value, waveInvoice.subtotal.currency.symbol)}
				</span>
			</div>

			{#if parseFloat(waveInvoice.discountTotal.value) > 0}
				<div class="flex items-center justify-between py-2">
					<span class="text-theme-secondary">Discounts</span>
					<span class="font-medium text-success-600 dark:text-success-400">
						-{formatCurrency(
							waveInvoice.discountTotal.value,
							waveInvoice.discountTotal.currency.symbol
						)}
					</span>
				</div>
			{/if}

			{#if parseFloat(waveInvoice.taxTotal.value) > 0}
				<div class="flex items-center justify-between py-2">
					<span class="text-theme-secondary">Tax</span>
					<span class="font-medium text-theme">
						{formatCurrency(waveInvoice.taxTotal.value, waveInvoice.taxTotal.currency.symbol)}
					</span>
				</div>
			{/if}

			<div class="flex items-center justify-between border-t border-theme py-3">
				<span class="font-medium text-theme">Total</span>
				<span class="text-lg font-bold text-accent6-600 dark:text-accent6-400">
					{formatCurrency(waveInvoice.total.value, waveInvoice.total.currency.symbol)}
				</span>
			</div>

			{#if parseFloat(waveInvoice.amountPaid.value) > 0}
				<div class="flex items-center justify-between py-2">
					<span class="text-theme-secondary">Amount Paid</span>
					<span class="font-medium text-success-600 dark:text-success-400">
						{formatCurrency(waveInvoice.amountPaid.value, waveInvoice.amountPaid.currency.symbol)}
					</span>
				</div>
			{/if}

			{#if parseFloat(waveInvoice.amountDue.value) > 0}
				<div class="flex items-center justify-between py-2">
					<span class="font-medium text-theme">Amount Due</span>
					<span class="text-lg font-bold text-theme">
						{formatCurrency(waveInvoice.amountDue.value, waveInvoice.amountDue.currency.symbol)}
					</span>
				</div>
			{/if}
		</div>
	</div>

	<!-- Line Items -->
	<div class="card-padded">
		<h4 class="mb-4 text-sm font-medium text-theme-muted">
			Line Items ({waveInvoice.items.length})
		</h4>

		<div class="space-y-2">
			{#each waveInvoice.items as item, index (index)}
				<div class="rounded-lg border border-theme bg-theme-secondary p-3">
					<div class="flex items-start justify-between gap-3">
						<div class="min-w-0 flex-1">
							<p class="font-medium text-theme">{item.product.name}</p>
							{#if item.description}
								<p class="mt-0.5 text-sm text-theme-muted">{item.description}</p>
							{/if}
							<p class="mt-1 text-xs text-theme-muted">
								{item.quantity} x {formatCurrency(String(item.unitPrice))}
							</p>
						</div>
						<span class="font-semibold text-theme">
							{formatCurrency(item.total.value)}
						</span>
					</div>
				</div>
			{/each}
		</div>
	</div>

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

		<div class="grid grid-cols-1 gap-4 sm:grid-cols-2">
			<div>
				<p class="text-sm text-theme-muted">Invoice Date</p>
				<p class="font-medium text-theme">{formatDate(waveInvoice.invoiceDate)}</p>
			</div>
			<div>
				<p class="text-sm text-theme-muted">Due Date</p>
				<p class="font-medium text-theme">{formatDate(waveInvoice.dueDate)}</p>
			</div>
			{#if waveInvoice.poNumber}
				<div>
					<p class="text-sm text-theme-muted">PO Number</p>
					<p class="font-medium text-theme">{waveInvoice.poNumber}</p>
				</div>
			{/if}
			{#if waveInvoice.lastSentAt}
				<div>
					<p class="text-sm text-theme-muted">Last Sent</p>
					<p class="font-medium text-theme">
						{formatDateTime(waveInvoice.lastSentAt)}
						{#if waveInvoice.lastSentVia}
							<span class="text-theme-muted">via {waveInvoice.lastSentVia}</span>
						{/if}
					</p>
				</div>
			{/if}
			{#if waveInvoice.lastViewedAt}
				<div>
					<p class="text-sm text-theme-muted">Last Viewed</p>
					<p class="font-medium text-theme">{formatDateTime(waveInvoice.lastViewedAt)}</p>
				</div>
			{/if}
		</div>
	</div>

	<!-- Notes -->
	{#if waveInvoice.memo || waveInvoice.footer}
		<div class="card-padded">
			<h4 class="mb-4 text-sm font-medium text-theme-muted">Notes</h4>

			<div class="space-y-4">
				{#if waveInvoice.memo}
					<div>
						<p class="text-sm font-medium text-theme">Memo</p>
						<p class="mt-1 text-sm text-theme-secondary">{waveInvoice.memo}</p>
					</div>
				{/if}
				{#if waveInvoice.footer}
					<div>
						<p class="text-sm font-medium text-theme">Footer</p>
						<p class="mt-1 text-sm text-theme-secondary">{waveInvoice.footer}</p>
					</div>
				{/if}
			</div>
		</div>
	{/if}
</div>
