<script lang="ts">
	import { UpdateCustomerStore } from '$houdini';
	import { offCanvas } from '$lib/stores/offCanvas.svelte';
	import { fromGlobalId } from '$lib/utils/relay';
	import IconSpinner from '$lib/components/icons/IconSpinner.svelte';

	interface WaveCustomer {
		id: string;
		name: string;
		email: string | null;
		isArchived: boolean;
	}

	interface Props {
		customerId: string;
		currentWaveCustomerId?: string | null;
		waveCustomers: WaveCustomer[];
		onSuccess?: () => void;
	}

	let { customerId, currentWaveCustomerId, waveCustomers, onSuccess }: Props = $props();

	let submitting = $state(false);
	let error = $state('');
	let searchQuery = $state('');
	// Store the decoded Wave customer ID (matches what backend stores)
	let selectedCustomerId = $derived<string | null>(null);

	// Sync selectedCustomerId when currentWaveCustomerId prop changes (e.g., when form reopens)
	// currentWaveCustomerId from backend is already decoded
	$effect(() => {
		selectedCustomerId = currentWaveCustomerId ?? null;
	});

	// Decode Wave ID to match backend storage format
	function decodeWaveId(id: string): string {
		return fromGlobalId(id);
	}

	// Filter customers by search query
	let filteredCustomers = $derived.by(() => {
		const active = waveCustomers.filter((c) => !c.isArchived);
		if (!searchQuery.trim()) return active;
		const query = searchQuery.toLowerCase();
		return active.filter((c) => {
			const name = c.name.toLowerCase();
			const email = c.email?.toLowerCase() ?? '';
			return name.includes(query) || email.includes(query);
		});
	});

	const updateStore = new UpdateCustomerStore();

	async function handleSave() {
		submitting = true;
		error = '';

		try {
			const res = await updateStore.mutate({
				input: {
					id: customerId,
					waveCustomerId: selectedCustomerId ?? ''
				}
			});

			if (res.errors?.length) {
				error = res.errors.map((e) => e.message).join(', ');
				return;
			}

			offCanvas.closeRight();
			onSuccess?.();
		} catch (err) {
			error = err instanceof Error ? err.message : 'Failed to save';
		} finally {
			submitting = false;
		}
	}

	function handleCancel() {
		offCanvas.closeRight();
	}
</script>

<div class="flex h-full flex-col">
	{#if error}
		<div class="mb-4 alert-error">
			{error}
		</div>
	{/if}

	<!-- Search -->
	<div class="mb-4">
		<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 Wave customers..."
				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"
			/>
		</div>
	</div>

	<!-- Customer List -->
	<div class="mb-4 min-h-0 flex-1 overflow-y-auto">
		{#if filteredCustomers.length === 0 && !searchQuery}
			<div class="py-8 text-center text-theme-muted">No Wave customers found.</div>
		{:else if filteredCustomers.length === 0}
			<div class="py-8 text-center text-theme-muted">No customers match your search.</div>
		{:else}
			<div class="space-y-2">
				<!-- Option to unlink -->
				<button
					type="button"
					onclick={() => (selectedCustomerId = null)}
					class="w-full rounded-lg border p-3 text-left transition-colors {selectedCustomerId ===
					null
						? 'border-primary-500 bg-primary-500/10'
						: 'border-theme bg-theme hover:bg-black/5 dark:hover:bg-white/10'}"
				>
					<span class="flex items-center gap-3">
						<span
							class="flex h-5 w-5 items-center justify-center rounded-full border-2 {selectedCustomerId ===
							null
								? 'border-primary-500'
								: 'border-theme-muted'}"
						>
							{#if selectedCustomerId === null}
								<div class="h-2.5 w-2.5 rounded-full bg-primary-500"></div>
							{/if}
						</span>
						<span class="text-theme-muted italic">No Wave customer (unlink)</span>
					</span>
				</button>

				{#each filteredCustomers as customer (customer.id)}
					{@const decodedId = decodeWaveId(customer.id)}
					<button
						type="button"
						onclick={() => (selectedCustomerId = decodedId)}
						class="w-full rounded-lg border p-3 text-left transition-colors {selectedCustomerId ===
						decodedId
							? 'border-primary-500 bg-primary-500/10'
							: 'border-theme bg-theme hover:bg-black/5 dark:hover:bg-white/10'}"
					>
						<span class="flex items-start gap-3">
							<span
								class="mt-0.5 flex h-5 w-5 flex-shrink-0 items-center justify-center rounded-full border-2 {selectedCustomerId ===
								decodedId
									? 'border-primary-500'
									: 'border-theme-muted'}"
							>
								{#if selectedCustomerId === decodedId}
									<div class="h-2.5 w-2.5 rounded-full bg-primary-500"></div>
								{/if}
							</span>
							<span class="min-w-0 flex-1">
								<span class="font-medium text-theme">{customer.name}</span>
								{#if customer.email}
									<p class="truncate text-sm text-theme-secondary">{customer.email}</p>
								{/if}
								<span class="truncate font-mono text-xs text-theme-muted">{decodedId}</span>
							</span>
						</span>
					</button>
				{/each}
			</div>
		{/if}
	</div>

	<!-- Actions -->
	<div class="flex items-center gap-3 border-t border-theme pt-4">
		<button
			type="button"
			onclick={handleSave}
			disabled={submitting}
			class="flex-1 rounded-lg bg-primary-500 px-4 py-2 font-medium text-white transition-colors hover:bg-primary-600 disabled:cursor-not-allowed disabled:opacity-50"
		>
			{#if submitting}
				<span class="flex items-center justify-center gap-2">
					<IconSpinner class="h-4 w-4" />
					<span>Saving...</span>
				</span>
			{:else}
				Save
			{/if}
		</button>
		<button
			type="button"
			onclick={handleCancel}
			disabled={submitting}
			class="rounded-lg border border-theme bg-theme px-4 py-2 font-medium text-theme transition-colors hover:bg-black/5 disabled:cursor-not-allowed disabled:opacity-50 dark:hover:bg-white/10"
		>
			Cancel
		</button>
	</div>
</div>
