<script lang="ts">
	import { offCanvas } from '$lib/stores/offCanvas.svelte';
	import WaveProductForm from './WaveProductForm.svelte';
	import type { WaveProduct } from './types';

	interface IncomeAccount {
		id: string;
		name: string;
		subtype: { value: string };
	}

	interface Props {
		products: WaveProduct[];
		archivedProducts: WaveProduct[];
		incomeAccounts: IncomeAccount[];
		onArchive: (product: WaveProduct) => void;
	}

	let { products, archivedProducts, incomeAccounts, onArchive }: Props = $props();

	let searchQuery = $state('');
	let showArchived = $state(false);

	let activeProducts = $derived.by(() => {
		const list = showArchived ? archivedProducts : products;
		if (!searchQuery.trim()) return list;
		const query = searchQuery.toLowerCase();
		return list.filter(
			(p) =>
				p.name.toLowerCase().includes(query) ||
				(p.description && p.description.toLowerCase().includes(query))
		);
	});

	function formatCurrency(value: number): string {
		return `$${value.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
	}

	function openCreateForm() {
		offCanvas.showRight({
			title: 'New Product/Service',
			content: createFormContent
		});
	}

	function openEditForm(product: WaveProduct) {
		selectedProduct = product;
		offCanvas.showRight({
			title: 'Edit Product/Service',
			content: editFormContent
		});
	}

	let selectedProduct = $state<WaveProduct | null>(null);
</script>

{#snippet createFormContent()}
	<WaveProductForm {incomeAccounts} />
{/snippet}

{#snippet editFormContent()}
	<WaveProductForm product={selectedProduct} {incomeAccounts} />
{/snippet}

<div class="space-y-4">
	<!-- Header with search, toggle, and add button -->
	<div class="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
		<div class="flex flex-1 flex-col gap-3 sm:flex-row sm:items-center">
			<div class="relative flex-1 sm:max-w-xs">
				<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 products..."
					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>

			{#if archivedProducts.length > 0}
				<label class="flex items-center gap-2 text-sm text-theme-secondary">
					<input
						type="checkbox"
						bind:checked={showArchived}
						class="h-4 w-4 rounded border-theme text-accent6-500 focus:ring-accent6-500"
					/>
					Show archived ({archivedProducts.length})
				</label>
			{/if}
		</div>

		{#if !showArchived}
			<button
				type="button"
				onclick={openCreateForm}
				class="flex items-center justify-center gap-2 rounded-lg bg-accent6-500 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-accent6-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="M12 4v16m8-8H4"
					/>
				</svg>
				Add Product
			</button>
		{/if}
	</div>

	<!-- Products List -->
	{#if activeProducts.length > 0}
		<div class="grid grid-cols-1 gap-4">
			{#each activeProducts as product (product.id)}
				<div
					class="flex min-w-0 items-start justify-between gap-4 rounded-lg border border-theme bg-theme-card p-4"
					class:opacity-60={showArchived}
				>
					<div class="min-w-0 flex-1">
						<div class="flex flex-wrap items-center gap-2">
							<h3 class="font-medium text-theme">{product.name}</h3>
							{#if showArchived}
								<span
									class="rounded-full bg-gray-500/10 px-2 py-0.5 text-xs font-medium text-gray-600 dark:text-gray-400"
								>
									Archived
								</span>
							{/if}
							{#if product.isSold}
								<span
									class="rounded-full bg-success-500/10 px-2 py-0.5 text-xs font-medium text-success-600 dark:text-success-400"
								>
									Sold
								</span>
							{/if}
							{#if product.isBought}
								<span
									class="rounded-full bg-primary-500/10 px-2 py-0.5 text-xs font-medium text-primary-600 dark:text-primary-400"
								>
									Bought
								</span>
							{/if}
						</div>
						{#if product.description}
							<p class="mt-1 line-clamp-2 text-sm text-theme-muted">{product.description}</p>
						{/if}
						<div class="mt-2 flex flex-wrap items-baseline gap-x-4 gap-y-1">
							<p class="text-lg font-semibold text-accent6-600 dark:text-accent6-400">
								{formatCurrency(product.unitPrice)}
							</p>
							{#if product.incomeAccount}
								<span class="text-sm text-theme-muted">
									{product.incomeAccount.name}
								</span>
							{/if}
						</div>
					</div>

					{#if !showArchived}
						<div class="flex flex-shrink-0 items-center gap-2">
							<button
								type="button"
								onclick={() => openEditForm(product)}
								class="rounded-lg p-2 text-theme-muted hover:bg-black/5 hover:text-theme dark:hover:bg-white/10"
								aria-label="Edit product"
							>
								<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>
							</button>
							<button
								type="button"
								onclick={() => onArchive(product)}
								class="rounded-lg p-2 text-theme-muted hover:bg-warning-500/10 hover:text-warning-600 dark:hover:text-warning-400"
								aria-label="Archive product"
								title="Archive product"
							>
								<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 8h14M5 8a2 2 0 110-4h14a2 2 0 110 4M5 8v10a2 2 0 002 2h10a2 2 0 002-2V8m-9 4h4"
									/>
								</svg>
							</button>
						</div>
					{/if}
				</div>
			{/each}
		</div>
	{:else if searchQuery}
		<div class="empty-state py-12">
			<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 Products Found</h2>
			<p class="empty-state-text">No products match your search criteria.</p>
		</div>
	{:else}
		<div class="empty-state py-12">
			<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="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"
				/>
			</svg>
			<h2 class="empty-state-title">No Products</h2>
			<p class="empty-state-text">Get started by creating your first product or service.</p>
			<button
				type="button"
				onclick={openCreateForm}
				class="mt-4 inline-flex items-center gap-2 rounded-lg bg-accent6-500 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-accent6-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="M12 4v16m8-8H4"
					/>
				</svg>
				Add Product
			</button>
		</div>
	{/if}
</div>
