<script lang="ts">
	import { createTask, updateTask } 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 Task = NonNullable<
		GetAccount$result['account']
	>['addresses'][number]['scopes'][number]['areas'][number]['tasks'][number];

	const FREQUENCY_OPTIONS = [
		{ value: 'daily', label: 'Daily' },
		{ value: 'weekly', label: 'Weekly' },
		{ value: 'monthly', label: 'Monthly' },
		{ value: 'quarterly', label: 'Quarterly' },
		{ value: 'triannual', label: 'Triannual (3x/year)' },
		{ value: 'annual', label: 'Annual' },
		{ value: 'as_needed', label: 'As Needed' }
	];

	const VALID_FREQUENCIES = new Set(FREQUENCY_OPTIONS.map((o) => o.value));

	// Sanitize frequency to ensure it's a valid enum value (lowercase)
	function sanitizeFrequency(freq: string | null | undefined): string {
		if (!freq) return 'weekly';
		const lower = freq.toLowerCase();
		if (VALID_FREQUENCIES.has(lower)) {
			return lower;
		}
		return 'weekly'; // Default to weekly for invalid/legacy values
	}

	interface Props {
		areaId: string;
		task?: Task;
		nextOrder?: number;
		onSuccess?: () => void;
		onCancel?: () => void;
	}

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

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

	let description = $state(task?.description ?? '');
	let checklistDescription = $state(task?.checklistDescription ?? '');
	let frequency = $state(sanitizeFrequency(task?.frequency));
	let order = $state(task?.order ?? nextOrder);

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

		try {
			if (!description.trim()) {
				error = 'Please provide a task description';
				return;
			}

			if (isEdit && task) {
				await updateTask({
					id: task.id,
					description: description.trim(),
					checklistDescription: checklistDescription.trim() || null,
					frequency,
					isConditional: false,
					order
				});
			} else {
				await createTask({
					areaId,
					description: description.trim(),
					checklistDescription: checklistDescription.trim() || null,
					frequency,
					isConditional: false,
					order
				});
			}

			offCanvas.closeRight();
			onSuccess?.();
		} catch (err) {
			error = err instanceof Error ? err.message : 'Failed to save task';
		} 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="description" class="mb-1.5 block text-sm font-medium text-theme">
				Task Description <span class="text-red-500">*</span>
			</label>
			<textarea
				id="description"
				bind:value={description}
				disabled={submitting}
				rows="2"
				placeholder="e.g., Empty trash cans and replace liners"
				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"
			></textarea>
		</div>

		<div>
			<label for="checklistDescription" class="mb-1.5 block text-sm font-medium text-theme">
				Checklist Note
			</label>
			<input
				id="checklistDescription"
				type="text"
				bind:value={checklistDescription}
				disabled={submitting}
				placeholder="Optional short note for checklist"
				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"
			/>
			<p class="mt-1 text-xs text-theme-muted">Shortened version shown on service checklists</p>
		</div>

		<div>
			<label for="frequency" class="mb-1.5 block text-sm font-medium text-theme">
				Frequency <span class="text-red-500">*</span>
			</label>
			<div class="relative w-full">
				<select
					id="frequency"
					bind:value={frequency}
					disabled={submitting}
					class="w-full appearance-none rounded-lg border border-theme bg-theme py-2 pr-10 pl-3 text-theme focus:border-primary-500 focus:ring-1 focus:ring-primary-500 disabled:cursor-not-allowed disabled:opacity-50"
				>
					{#each FREQUENCY_OPTIONS as option (option.value)}
						<option value={option.value}>{option.label}</option>
					{/each}
				</select>
				<div class="pointer-events-none absolute inset-y-0 right-0 flex items-center pr-3">
					<svg
						class="h-4 w-4 text-theme-muted"
						style="fill: none"
						stroke="currentColor"
						viewBox="0 0 24 24"
					>
						<path
							stroke-linecap="round"
							stroke-linejoin="round"
							stroke-width="2"
							d="M19 9l-7 7-7-7"
						/>
					</svg>
				</div>
			</div>
		</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"
			/>
		</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 Task'}
				{/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>
