<script lang="ts">
	import { client } from '$lib/graphql/client';
	import { CREATE_SERVICE_SCOPE, UPDATE_SERVICE_SCOPE } from '$lib/graphql/mutations/location';
	import { CREATE_SERVICE_SCOPE_FROM_TEMPLATE } from '$lib/graphql/mutations/service-scope-template';
	import {
		SERVICE_SCOPE_TEMPLATES_QUERY,
		type ServiceScopeTemplatesQueryResult,
		type ServiceScopeTemplateListItem
	} from '$lib/graphql/queries/service-scope-templates';
	import type { AddressScope } from '$lib/graphql/queries/account';

	interface Props {
		scope?: AddressScope | null;
		accountId: string;
		accountAddressId: string;
		onSuccess: () => void;
		onCancel: () => void;
	}

	let { scope, accountId, accountAddressId, onSuccess, onCancel }: Props = $props();

	let isEdit = $derived(!!scope);

	// Form state - use $effect to sync from props
	let name = $state('');
	let description = $state('');
	let selectedTemplateId = $state<string | null>(null);
	let createMode = $state<'blank' | 'template'>('blank');

	// Sync form state from props
	$effect(() => {
		name = scope?.name ?? '';
		description = scope?.description ?? '';
	});

	// Templates
	let templates = $state<ServiceScopeTemplateListItem[]>([]);
	let loadingTemplates = $state(false);

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

	// Load templates on mount
	$effect(() => {
		if (!isEdit) {
			loadTemplates();
		}
	});

	async function loadTemplates() {
		loadingTemplates = true;
		try {
			const result = await client.query<ServiceScopeTemplatesQueryResult>({
				query: SERVICE_SCOPE_TEMPLATES_QUERY,
				variables: { isActive: true },
				fetchPolicy: 'network-only'
			});
			templates = result.data?.serviceScopeTemplates ?? [];
		} catch (err) {
			console.error('Failed to load templates:', err);
		} finally {
			loadingTemplates = false;
		}
	}

	function handleModeChange(event: Event) {
		const target = event.currentTarget as HTMLSelectElement;
		createMode = target.value as 'blank' | 'template';
		if (createMode === 'blank') {
			selectedTemplateId = null;
		}
	}

	function handleTemplateChange(event: Event) {
		const target = event.currentTarget as HTMLSelectElement;
		selectedTemplateId = target.value || null;
		// Auto-fill name from template
		if (selectedTemplateId) {
			const template = templates.find((t) => t.id === selectedTemplateId);
			if (template) {
				name = template.name;
				description = template.description ?? '';
			}
		}
	}

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

		try {
			if (isEdit && scope) {
				await client.mutate({
					mutation: UPDATE_SERVICE_SCOPE,
					variables: {
						id: scope.id,
						input: {
							name: name || undefined,
							description: description || undefined
						}
					}
				});
			} else if (createMode === 'template' && selectedTemplateId) {
				await client.mutate({
					mutation: CREATE_SERVICE_SCOPE_FROM_TEMPLATE,
					variables: {
						templateId: selectedTemplateId,
						accountId,
						accountAddressId
					}
				});
			} else {
				await client.mutate({
					mutation: CREATE_SERVICE_SCOPE,
					variables: {
						accountId,
						accountAddressId,
						input: {
							name,
							description: description || undefined
						}
					}
				});
			}

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

	let selectedTemplate = $derived(templates.find((t) => t.id === selectedTemplateId));
</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}

	{#if !isEdit && templates.length > 0}
		<div>
			<label for="createMode" class="form-label">Create From</label>
			<select id="createMode" class="select-base" onchange={handleModeChange} disabled={loading}>
				<option value="blank" selected={createMode === 'blank'}>Blank Scope</option>
				<option value="template" selected={createMode === 'template'}>Template</option>
			</select>
		</div>

		{#if createMode === 'template'}
			<div>
				<label for="template" class="form-label">
					Select Template <span class="required-indicator">*</span>
				</label>
				<select
					id="template"
					class="select-base"
					onchange={handleTemplateChange}
					disabled={loading || loadingTemplates}
					required
				>
					<option value="">Choose a template...</option>
					{#each templates as template (template.id)}
						<option value={template.id} selected={selectedTemplateId === template.id}>
							{template.name} ({template.areaCount} areas, {template.taskCount} tasks)
						</option>
					{/each}
				</select>
			</div>

			{#if selectedTemplate}
				<div
					class="rounded-lg border border-secondary-500/30 bg-secondary-50/50 p-3 dark:bg-secondary-950/30"
				>
					<p class="text-sm font-medium text-secondary-700 dark:text-secondary-400">
						{selectedTemplate.name}
					</p>
					{#if selectedTemplate.description}
						<p class="mt-1 text-sm text-secondary-600 dark:text-secondary-500">
							{selectedTemplate.description}
						</p>
					{/if}
					<p class="mt-2 text-xs text-secondary-600 dark:text-secondary-500">
						This will create a scope with {selectedTemplate.areaCount} area{selectedTemplate.areaCount !==
						1
							? 's'
							: ''}
						and {selectedTemplate.taskCount} task{selectedTemplate.taskCount !== 1 ? 's' : ''}.
					</p>
				</div>
			{/if}
		{/if}
	{/if}

	{#if isEdit || createMode === 'blank'}
		<div>
			<label for="name" class="form-label">
				Scope Name <span class="required-indicator">*</span>
			</label>
			<input
				id="name"
				type="text"
				bind:value={name}
				class="input-base"
				required
				disabled={loading}
				placeholder="e.g., Standard Cleaning Scope"
			/>
		</div>

		<div>
			<label for="description" class="form-label">Description</label>
			<textarea
				id="description"
				bind:value={description}
				class="textarea-base"
				rows="3"
				disabled={loading}
				placeholder="General notes about the scope of work..."
			></textarea>
		</div>
	{/if}

	{#if !isEdit}
		<div
			class="rounded-lg border border-primary-500/30 bg-primary-50/50 p-3 dark:bg-primary-950/30"
		>
			<p class="text-sm text-primary-700 dark:text-primary-400">
				{#if createMode === 'template'}
					Creating from a template will copy all areas and tasks. Any existing active scope will be
					deactivated.
				{:else}
					Creating a new scope will automatically deactivate any existing active scope. You can add
					areas and tasks after creating the scope.
				{/if}
			</p>
		</div>
	{/if}

	{#if isEdit && scope?.areas && scope.areas.length > 0}
		<div class="bg-theme-secondary/30 rounded-lg border border-theme p-3">
			<p class="text-sm text-theme-muted">
				This scope has {scope.areas.length} area{scope.areas.length === 1 ? '' : 's'} with tasks. Editing
				areas and tasks is coming soon.
			</p>
		</div>
	{/if}

	<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 || (createMode === 'template' && !selectedTemplateId)}
		>
			{#if loading}
				Saving...
			{:else if isEdit}
				Update Scope
			{:else if createMode === 'template'}
				Create from Template
			{:else}
				Create Scope
			{/if}
		</button>
	</div>
</form>
