<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 { AccountCreateForm } 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(accountId: string) {
		closeDrawer();
		await goto(`/admin/accounts/${accountId}`);
	}

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

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

	let filteredAccounts = $derived(
		accounts.filter((a) => {
			// Search by name, customer name, city, or state (case-insensitive)
			if (searchQuery) {
				const query = searchQuery.toLowerCase();
				const matchesName = a.name.toLowerCase().includes(query);
				const matchesCustomer = a.customer?.name.toLowerCase().includes(query) ?? false;
				const matchesLocation = a.addresses.some(
					(addr) =>
						addr.city.toLowerCase().includes(query) || addr.state.toLowerCase().includes(query)
				);
				if (!matchesName && !matchesCustomer && !matchesLocation) {
					return false;
				}
			}

			// Status filter
			return !(statusFilter !== 'ALL' && a.status !== statusFilter);


		})
	);

	// Statistics
	let totalCount = $derived(accounts.length);
	let filteredCount = $derived(filteredAccounts.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';
		}
	}

	function getPrimaryAddress(account: (typeof accounts)[number]) {
		return account.addresses.find((a) => a.isPrimary) ?? account.addresses[0] ?? null;
	}

	function hasWaveLinkedRevenue(account: (typeof accounts)[number]): boolean {
		return account.revenues.some((r) => r.isActive && r.waveServiceId);
	}
</script>

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

<div class="py-8">
	<ContentContainer>
		<!-- Header -->
		<AdminDashboardHeader title="Accounts">
			{#snippet subtitleSnippet()}
				{#if statusFilter === 'ALL'}
					{totalCount} total accounts
				{:else}
					{filteredCount} of {totalCount} accounts
				{/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 Account
				</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 by account, customer, or city..."
					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>

		<!-- Account List -->
		{#if filteredAccounts.length > 0}
			<div class="grid grid-cols-1 gap-4 sm:grid-cols-2">
				{#each filteredAccounts as account (account.id)}
					<a
						href="/admin/accounts/{account.id}"
						class="flex items-center justify-between card-account"
					>
						<div>
							<h2 class="text-lg font-semibold text-theme">{account.name}</h2>
							{#if account.customer}
								<p class="mt-1 text-sm text-theme-muted">{account.customer.name}</p>
							{/if}
							{#if getPrimaryAddress(account)}
								<p class="text-sm text-theme-muted">
									{getPrimaryAddress(account).city}, {getPrimaryAddress(account).state}
								</p>
							{/if}
							<div class="mt-2 flex flex-wrap items-center gap-2">
								<span
									class="inline-flex rounded-full px-2 py-0.5 text-xs font-semibold {getStatusBadgeClass(
										account.status
									)}"
								>
									{account.status}
								</span>
								{#if hasWaveLinkedRevenue(account)}
									<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 accounts found</h3>
				<p class="mt-2 text-theme-secondary">No accounts 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="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4"
					/>
				</svg>
				<h3 class="mt-4 text-lg font-medium text-theme">No accounts yet</h3>
				<p class="mt-2 text-theme-secondary">Get started by adding your first account.</p>
			</div>
		{/if}
	</ContentContainer>
</div>

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