<script lang="ts">
	import { client } from '$lib/graphql/client';
	import { CREATE_PROJECT_SCOPE, UPDATE_PROJECT_SCOPE } from '$lib/graphql/mutations/project';
	import { CREATE_PROJECT_SCOPE_FROM_TEMPLATE } from '$lib/graphql/mutations/project-scope-template';
	import {
		PROJECT_SCOPE_TEMPLATES_QUERY,
		type ProjectScopeTemplatesQueryResult,
		type ProjectScopeTemplateListItem
	} from '$lib/graphql/queries/project-scope-templates';
	import type { ProjectScope } from '$lib/graphql/queries/projects';

	interface Props {
		scope?: ProjectScope | null;
		projectId: string;
		onSuccess: () => void;
		onCancel: () => void;
	}

	let { scope, projectId, 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<ProjectScopeTemplateListItem[]>([]);
	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<ProjectScopeTemplatesQueryResult>({
				query: PROJECT_SCOPE_TEMPLATES_QUERY,
				variables: { isActive: true },
				fetchPolicy: 'network-only'
			});
			templates = result.data?.projectScopeTemplates ?? [];
		} 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_PROJECT_SCOPE,
					variables: {
						id: scope.id,
						input: {
							name: name || undefined,
							description: description || undefined
						}
					}
				});
			} else if (createMode === 'template' && selectedTemplateId) {
				await client.mutate({
					mutation: CREATE_PROJECT_SCOPE_FROM_TEMPLATE,
					variables: {
						templateId: selectedTemplateId,
						projectId
					}
				});
			} else {
				await client.mutate({
					mutation: CREATE_PROJECT_SCOPE,
					variables: {
						projectId,
						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.categoryCount} categories, {template.taskCount} tasks)
						</option>
					{/each}
				</select>
			</div>

			{#if selectedTemplate}
				<div
					class="rounded-lg border border-accent-500/30 bg-accent-50/50 p-3 dark:bg-accent-950/30"
				>
					<p class="text-sm font-medium text-accent-700 dark:text-accent-400">
						{selectedTemplate.name}
					</p>
					{#if selectedTemplate.description}
						<p class="mt-1 text-sm text-accent-600 dark:text-accent-500">
							{selectedTemplate.description}
						</p>
					{/if}
					<p class="mt-2 text-xs text-accent-600 dark:text-accent-500">
						This will create a scope with {selectedTemplate.categoryCount} categor{selectedTemplate.categoryCount !==
						1
							? 'ies'
							: 'y'}
						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., Window 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 project scope..."
			></textarea>
		</div>
	{/if}

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

	{#if isEdit && scope?.categories && scope.categories.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.categories.length} categor{scope.categories.length === 1
					? 'y'
					: 'ies'} with tasks.
			</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>
