<script lang="ts">
	import { createArea, updateArea } from '$lib/utils/scopes';
	import { offCanvas } from '$lib/stores/offCanvas.svelte';
	import type { GetAccount$result } from '$houdini';
	import IconSpinner from '$lib/components/icons/IconSpinner.svelte';

	type Area = NonNullable<
		GetAccount$result['account']
	>['addresses'][number]['scopes'][number]['areas'][number];

	interface Props {
		scopeId: string;
		area?: Area;
		nextOrder?: number;
		onSuccess?: () => void;
		onCancel?: () => void;
	}

	let { scopeId, area, nextOrder = 0, onSuccess, onCancel }: Props = $props();

	let isEdit = $derived(!!area);
	let submitting = $state(false);
	let error = $state('');

	let name = $state(area?.name ?? '');
	let order = $state(area?.order ?? nextOrder);

	async function handleSubmit(e: SubmitEvent) {
		e.preventDefault();
		submitting = true;
		error = '';

		try {
			if (!name.trim()) {
				error = 'Please provide an area name';
				return;
			}

			if (isEdit && area) {
				await updateArea({
					id: area.id,
					name: name.trim(),
					order
				});
			} else {
				await createArea({
					scopeId,
					name: name.trim(),
					order
				});
			}

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

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

<div class="min-w-0 space-y-6">
	{#if error}
		<div class="alert-error">
			{error}
		</div>
	{/if}

	<form class="space-y-4" onsubmit={handleSubmit}>
		<div>
			<label for="name" class="mb-1.5 block text-sm font-medium text-theme">
				Area Name <span class="text-red-500">*</span>
			</label>
			<input
				id="name"
				type="text"
				bind:value={name}
				disabled={submitting}
				placeholder="e.g., Kitchen, Lobby, Restrooms"
				class="placeholder-theme-muted w-full rounded-lg border border-theme bg-theme px-3 py-2 text-theme focus:border-primary-500 focus:ring-1 focus:ring-primary-500 disabled:cursor-not-allowed disabled:opacity-50"
			/>
		</div>

		<div>
			<label for="order" class="mb-1.5 block text-sm font-medium text-theme"> Display Order </label>
			<input
				id="order"
				type="number"
				min="0"
				bind:value={order}
				disabled={submitting}
				class="w-full rounded-lg border border-theme bg-theme px-3 py-2 text-theme focus:border-primary-500 focus:ring-1 focus:ring-primary-500 disabled:cursor-not-allowed disabled:opacity-50"
			/>
			<p class="mt-1 text-xs text-theme-muted">Lower numbers appear first</p>
		</div>

		<div class="flex items-center gap-3 pt-4">
			<button
				type="submit"
				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>{isEdit ? 'Saving...' : 'Creating...'}</span>
					</span>
				{:else}
					{isEdit ? 'Save Changes' : 'Add Area'}
				{/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>
	</form>
</div>
