<script lang="ts">
	import type { PageData } from './$types';
	import ContentContainer from '$lib/components/layout/ContentContainer.svelte';
	import AccountForm from '$lib/components/admin/accounts/AccountForm.svelte';
	import { offCanvas } from '$lib/stores/offCanvas.svelte';
	import { invalidateAll, goto } from '$app/navigation';
	import { page } from '$app/state';

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

	// Auto-open create form if action=create is in URL
	$effect(() => {
		if (page.url.searchParams.get('action') === 'create') {
			showCreateForm();
			// Remove the action param from URL without navigation
			goto('/admin/accounts', { replaceState: true, noScroll: true });
		}
	});

	let accounts = $derived(data.accounts?.data?.accounts ?? []);
	let customers = $derived(data.customers?.data?.customers ?? []);
	let customerLookup = $derived(data.customerLookup ?? {});
	let searchQuery = $state('');

	let filteredAccounts = $derived(
		accounts.filter((a) => a.name.toLowerCase().includes(searchQuery.toLowerCase()))
	);

	function showCreateForm() {
		offCanvas.showRight({
			title: 'Create Account',
			content: createFormContent
		});
	}

	async function handleSuccess() {
		await invalidateAll();
	}

	function getCustomerName(customerId: string | null | undefined): string {
		if (!customerId) return 'No customer';
		const customer = customerLookup.get(customerId);
		return customer?.customerName ?? 'Unknown';
	}
</script>

{#snippet createFormContent()}
	<AccountForm {customers} onSuccess={handleSuccess} />
{/snippet}

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

<div class="py-8">
	<ContentContainer>
		<div class="mb-8">
			<div class="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
				<div class="flex items-start gap-4">
					<a
						href="/admin"
						class="rounded-lg p-1 text-theme-muted hover:bg-black/5 hover:text-theme dark:hover:bg-white/10"
						aria-label="Go back"
					>
						<svg class="h-5 w-5" style="fill: none" stroke="currentColor" viewBox="0 0 24 24">
							<path
								stroke-linecap="round"
								stroke-linejoin="round"
								stroke-width="2"
								d="M15 19l-7-7 7-7"
							/>
						</svg>
					</a>
					<div>
						<h1 class="text-2xl font-bold text-primary-600 md:text-3xl dark:text-primary-400">
							Accounts
						</h1>
						<p class="mt-2 text-theme-secondary">Manage service accounts and locations.</p>
					</div>
				</div>
				<button
					type="button"
					onclick={showCreateForm}
					class="hidden items-center gap-2 rounded-lg bg-primary-500 px-4 py-2 text-white transition-colors hover:bg-primary-600 sm:inline-flex"
				>
					<svg class="h-5 w-5" 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>
					<span>Add Account</span>
				</button>
			</div>
		</div>

		<!-- Search -->
		<div class="mb-6">
			<div class="relative">
				<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 accounts..."
					class="placeholder-theme-muted w-full rounded-lg border border-theme bg-theme-card py-2 pr-4 pl-10 text-theme focus:border-primary-500 focus:ring-1 focus:ring-primary-500"
				/>
			</div>
		</div>

		{#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>
							<p class="text-sm text-theme-secondary">
								{getCustomerName(account.customerId)}
							</p>
							<div class="flex items-center gap-2">
								{#if account.primaryAddress}
									<p class="text-sm text-theme-muted">
										{account.primaryAddress.city}, {account.primaryAddress.state}
									</p>
								{/if}
								{#if account.revenues?.some((r) => r.waveServiceId)}
									<span class="badge-primary">Linked</span>
								{/if}
							</div>
						</div>
						<svg
							class="h-5 w-5 flex-shrink-0 text-theme-muted"
							style="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}
			<div class="empty-state">
				<svg class="empty-state-icon" 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 accounts found</h2>
				<p class="empty-state-text">
					No accounts match "{searchQuery}". Try a different search term.
				</p>
			</div>
		{:else}
			<div class="empty-state">
				<svg class="empty-state-icon" style="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>
				<h2 class="empty-state-title">No accounts yet</h2>
				<p class="empty-state-text">Get started by adding your first service account.</p>
				<button
					type="button"
					onclick={showCreateForm}
					class="mt-4 inline-flex items-center gap-2 rounded-lg bg-primary-500 px-4 py-2 text-white transition-colors hover:bg-primary-600"
				>
					<svg class="h-5 w-5" 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>
					<span>Add Account</span>
				</button>
			</div>
		{/if}
	</ContentContainer>
</div>

<!-- Mobile FAB -->
<button
	type="button"
	onclick={showCreateForm}
	class="fixed right-4 bottom-20 z-30 flex h-14 w-14 items-center justify-center rounded-full bg-primary-500 text-white shadow-lg transition-colors hover:bg-primary-600 sm:hidden"
	aria-label="Add account"
>
	<svg class="h-6 w-6" 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>
</button>
