<script lang="ts">
	import { client } from '$lib/graphql/client';
	import {
		CREATE_PROJECT_SCOPE_TASK,
		UPDATE_PROJECT_SCOPE_TASK
	} from '$lib/graphql/mutations/project';
	import type { ProjectScopeTask } from '$lib/graphql/queries/projects';

	interface Props {
		task?: ProjectScopeTask | null;
		categoryId: string;
		onSuccess: () => void;
		onCancel: () => void;
	}

	let { task, categoryId, onSuccess, onCancel }: Props = $props();

	let isEdit = $derived(!!task);

	// Form state - use $effect to sync from props (no frequency - project tasks are one-time)
	let scopeDescription = $state('');
	let checklistDescription = $state('');
	let sessionDescription = $state('');
	let order = $state<number | null>(null);
	let estimatedMinutes = $state<number | null>(null);

	$effect(() => {
		scopeDescription = task?.scopeDescription ?? '';
		checklistDescription = task?.checklistDescription ?? '';
		sessionDescription = task?.sessionDescription ?? '';
		order = task?.order ?? null;
		estimatedMinutes = task?.estimatedMinutes ?? 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 && task) {
				await client.mutate({
					mutation: UPDATE_PROJECT_SCOPE_TASK,
					variables: {
						id: task.id,
						input: {
							scopeDescription: scopeDescription || undefined,
							checklistDescription: checklistDescription || undefined,
							sessionDescription: sessionDescription || undefined,
							order: order ?? undefined,
							estimatedMinutes: estimatedMinutes || undefined
						}
					}
				});
			} else {
				await client.mutate({
					mutation: CREATE_PROJECT_SCOPE_TASK,
					variables: {
						categoryId,
						input: {
							scopeDescription,
							checklistDescription: checklistDescription || undefined,
							sessionDescription: sessionDescription || undefined,
							order: order ?? undefined,
							estimatedMinutes: estimatedMinutes || 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="scopeDescription" class="form-label">
			Task Description <span class="required-indicator">*</span>
		</label>
		<input
			id="scopeDescription"
			type="text"
			bind:value={scopeDescription}
			class="input-base"
			required
			disabled={loading}
			placeholder="e.g., Clean interior windows, Polish frames"
		/>
		<p class="mt-1 text-xs text-theme-muted">Customer-facing description for scope documents</p>
	</div>

	<div>
		<label for="checklistDescription" class="form-label">Checklist</label>
		<input
			id="checklistDescription"
			type="text"
			bind:value={checklistDescription}
			class="input-base"
			disabled={loading}
			placeholder="Optional: shorter version for QA punchlists"
		/>
	</div>

	<div>
		<label for="sessionDescription" class="form-label">Work Instructions</label>
		<input
			id="sessionDescription"
			type="text"
			bind:value={sessionDescription}
			class="input-base"
			disabled={loading}
			placeholder="Optional: what team members see during work"
		/>
	</div>

	<div class="grid grid-cols-2 gap-4">
		<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"
			/>
		</div>

		<div>
			<label for="estimatedMinutes" class="form-label">Est. Minutes</label>
			<input
				id="estimatedMinutes"
				type="number"
				bind:value={estimatedMinutes}
				class="input-base"
				disabled={loading}
				min="0"
				placeholder="Optional"
			/>
		</div>
	</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 Task
			{:else}
				Add Task
			{/if}
		</button>
	</div>
</form>
