<script lang="ts">
	import { client } from '$lib/graphql/client';
	import { CREATE_SCOPE_AREA, UPDATE_SCOPE_AREA } from '$lib/graphql/mutations/location';

	interface Area {
		id: string;
		name: string;
		order: number;
	}

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

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

	let isEdit = $derived(!!area);

	// Form state - use $effect to sync from props
	let name = $state('');
	let order = $state<number | null>(null);

	$effect(() => {
		name = area?.name ?? '';
		order = area?.order ?? null;
	});

	let loading = $state(false);
	let error = $state<string | null>(null);

	async function handleSubmit(event: SubmitEvent) {
		event.preventDefault();
		loading = true;
		error = null;

		try {
			if (isEdit && area) {
				await client.mutate({
					mutation: UPDATE_SCOPE_AREA,
					variables: {
						id: area.id,
						input: {
							name: name || undefined,
							order: order ?? undefined
						}
					}
				});
			} else {
				await client.mutate({
					mutation: CREATE_SCOPE_AREA,
					variables: {
						scopeId,
						input: {
							name,
							order: order ?? undefined
						}
					}
				});
			}

			onSuccess();
		} catch (err) {
			error = err instanceof Error ? err.message : 'An error occurred';
		} finally {
			loading = false;
		}
	}
</script>

<form onsubmit={handleSubmit} class="space-y-5">
	{#if error}
		<div class="rounded-lg border border-error-500/30 bg-error-50/50 p-3 dark:bg-error-950/30">
			<p class="text-sm text-error-700 dark:text-error-400">{error}</p>
		</div>
	{/if}

	<div>
		<label for="name" class="form-label">
			Area Name <span class="required-indicator">*</span>
		</label>
		<input
			id="name"
			type="text"
			bind:value={name}
			class="input-base"
			required
			disabled={loading}
			placeholder="e.g., Main Lobby, Restrooms, Break Room"
		/>
	</div>

	<div>
		<label for="order" class="form-label">Order</label>
		<input
			id="order"
			type="number"
			bind:value={order}
			class="input-base"
			disabled={loading}
			min="0"
			placeholder="e.g., 10, 20, 30"
		/>
		<p class="mt-1 text-xs text-theme-muted">Lower numbers appear first</p>
	</div>

	<div class="form-actions border-t border-theme pt-5">
		<button type="button" class="btn-cancel" onclick={onCancel} disabled={loading}>Cancel</button>
		<button type="submit" class="btn-submit" disabled={loading}>
			{#if loading}
				Saving...
			{:else if isEdit}
				Update Area
			{:else}
				Add Area
			{/if}
		</button>
	</div>
</form>
