<script lang="ts">
	import type { PageData } from './$types';
	import { goto } from '$app/navigation';
	import { ContentContainer } from '$lib/components/layout';
	import { FormDrawer } from '$lib/components/drawers';
	import { CustomerCreateForm } from '$lib/components/forms';
	import { AdminDashboardHeader } from '$lib/components/admin';

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

	// Drawer state
	let drawerOpen = $state(false);

	function handleCreate() {
		drawerOpen = true;
	}

	function closeDrawer() {
		drawerOpen = false;
	}

	async function handleCreateSuccess(customerId: string) {
		closeDrawer();
		await goto(`/admin/customers/${customerId}`);
	}

	// Reactive state using Svelte 5 runes
	let searchQuery = $state('');
	let statusFilter = $state<'ALL' | 'ACTIVE' | 'INACTIVE' | 'PENDING'>('ALL');

	// Derived data
	let customers = $derived(data.customers ?? []);

	let filteredCustomers = $derived(
		customers.filter((c) => {
			// Name search (case-insensitive)
			if (searchQuery && !c.name.toLowerCase().includes(searchQuery.toLowerCase())) {
				return false;
			}

			// Status filter
			if (statusFilter !== 'ALL' && c.status !== statusFilter) {
				return false;
			}

			return true;
		})
	);

	// Statistics
	let totalCount = $derived(customers.length);
	let filteredCount = $derived(filteredCustomers.length);

	function clearFilters() {
		searchQuery = '';
		statusFilter = 'ALL';
	}

	function getStatusBadgeClass(status: string): string {
		switch (status) {
			case 'ACTIVE':
				return 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400';
			case 'INACTIVE':
				return 'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-300';
			case 'PENDING':
				return 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-400';
			default:
				return 'bg-gray-100 text-gray-800';
		}
	}
</script>

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

<div class="py-8">
	<ContentContainer>
		<!-- Header -->
		<AdminDashboardHeader title="Customers">
			{#snippet subtitleSnippet()}
				{#if statusFilter === 'ALL'}
					{totalCount} total customers
				{:else}
					{filteredCount} of {totalCount} customers
				{/if}
			{/snippet}
			{#snippet actions()}
				<button
					type="button"
					class="btn-primary flex w-full items-center justify-center gap-2 sm:w-auto sm:justify-start"
					onclick={handleCreate}
				>
					<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 4v16m8-8H4"
						/>
					</svg>
					Create Customer
				</button>
			{/snippet}
		</AdminDashboardHeader>

		<!-- Filters -->
		<div class="mb-6 space-y-4">
			<!-- Search -->
			<div class="relative">
				<svg
					class="absolute top-1/2 left-3 h-5 w-5 -translate-y-1/2 text-theme-muted"
					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 customers by name..."
					class="placeholder-theme-muted w-full rounded-lg border border-theme bg-theme py-2 pr-4 pl-10 text-theme focus:border-primary-500 focus:ring-1 focus:ring-primary-500 focus:outline-none"
				/>
			</div>

			<!-- Filter Controls -->
			<div class="flex flex-wrap items-center gap-4">
				<!-- Status Filter -->
				<div class="flex items-center gap-2">
					<label for="status-filter" class="text-sm font-medium text-theme-secondary">
						Status:
					</label>
					<select
						id="status-filter"
						bind:value={statusFilter}
						class="rounded-lg border border-theme bg-theme px-3 py-1.5 text-sm text-theme focus:border-primary-500 focus:ring-1 focus:ring-primary-500 focus:outline-none"
					>
						<option value="ALL">All Statuses</option>
						<option value="ACTIVE">Active</option>
						<option value="INACTIVE">Inactive</option>
						<option value="PENDING">Pending</option>
					</select>
				</div>

				<!-- Clear Filters -->
				{#if searchQuery || statusFilter !== 'ALL'}
					<button
						type="button"
						onclick={clearFilters}
						class="text-sm text-primary-500 hover:text-primary-600"
					>
						Clear filters
					</button>
				{/if}

				<!-- Results Count -->
				<span class="ml-auto text-sm text-theme-muted">
					Showing {filteredCount} of {totalCount}
				</span>
			</div>
		</div>

		<!-- Customer List -->
		{#if filteredCustomers.length > 0}
			<div class="grid grid-cols-1 gap-4 sm:grid-cols-2">
				{#each filteredCustomers as customer (customer.id)}
					<a
						href="/admin/customers/{customer.id}"
						class="flex items-center justify-between card-customer"
					>
						<div>
							<h2 class="text-lg font-semibold text-theme">{customer.name}</h2>
							<p class="mt-1 text-sm text-theme-muted">
								{customer.accounts.length} account{customer.accounts.length !== 1 ? 's' : ''}
							</p>
							<div class="mt-2 flex items-center gap-2">
								<span
									class="inline-flex rounded-full px-2 py-0.5 text-xs font-semibold {getStatusBadgeClass(
										customer.status
									)}"
								>
									{customer.status}
								</span>
								{#if customer.waveCustomerId}
									<span class="badge-primary">Wave Linked</span>
								{/if}
							</div>
						</div>
						<svg
							class="h-5 w-5 shrink-0 text-theme-muted"
							fill="none"
							stroke="currentColor"
							viewBox="0 0 24 24"
						>
							<path
								stroke-linecap="round"
								stroke-linejoin="round"
								stroke-width="2"
								d="M9 5l7 7-7 7"
							/>
						</svg>
					</a>
				{/each}
			</div>
		{:else if searchQuery || statusFilter !== 'ALL'}
			<!-- No results with filters -->
			<div class="rounded-lg border border-theme bg-theme-secondary py-12 text-center">
				<svg
					class="mx-auto h-12 w-12 text-theme-muted"
					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>
				<h3 class="mt-4 text-lg font-medium text-theme">No customers found</h3>
				<p class="mt-2 text-theme-secondary">No customers match your current filters.</p>
				<button
					type="button"
					onclick={clearFilters}
					class="mt-4 text-primary-500 hover:text-primary-600"
				>
					Clear all filters
				</button>
			</div>
		{:else}
			<!-- Empty state -->
			<div class="rounded-lg border border-theme bg-theme-secondary py-12 text-center">
				<svg
					class="mx-auto h-12 w-12 text-theme-muted"
					fill="none"
					stroke="currentColor"
					viewBox="0 0 24 24"
				>
					<path
						stroke-linecap="round"
						stroke-linejoin="round"
						stroke-width="1.5"
						d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z"
					/>
				</svg>
				<h3 class="mt-4 text-lg font-medium text-theme">No customers yet</h3>
				<p class="mt-2 text-theme-secondary">Get started by adding your first customer.</p>
			</div>
		{/if}
	</ContentContainer>
</div>

<!-- Create Customer Drawer -->
<FormDrawer open={drawerOpen} title="New Customer" onClose={closeDrawer}>
	<CustomerCreateForm onSuccess={handleCreateSuccess} onCancel={closeDrawer} />
</FormDrawer>
