<script lang="ts">
	interface TaskTemplate {
		id: string;
		description: string;
		checklistDescription: string | null;
		frequency?: string | null;
		estimatedMinutes: number | null;
	}

	interface Props {
		task: TaskTemplate;
		variant: 'service' | 'project';
		isEditing: boolean;
		onStartEdit: () => void;
		onCancelEdit: () => void;
		onSave: (updates: {
			description: string;
			checklistDescription: string;
			frequency?: string;
			estimatedMinutes: number | null;
		}) => void;
		onDelete: () => void;
		onMoveUp?: () => void;
		onMoveDown?: () => void;
	}

	let { task, variant, isEditing, onStartEdit, onCancelEdit, onSave, onDelete, onMoveUp, onMoveDown }: Props = $props();

	function formatFrequency(frequency: string | null | undefined): string {
		const lower = frequency?.toLowerCase();
		switch (lower) {
			case 'daily':
				return 'Daily';
			case 'weekly':
				return 'Weekly';
			case 'monthly':
				return 'Monthly';
			case 'quarterly':
				return 'Quarterly';
			case 'triannual':
				return '3x/Year';
			case 'annual':
				return 'Annual';
			case 'as_needed':
				return 'As Needed';
			default:
				return frequency ?? 'Weekly';
		}
	}

	function handleSubmit(e: SubmitEvent) {
		e.preventDefault();
		const form = e.currentTarget as HTMLFormElement;
		const formData = new FormData(form);
		const updates: Parameters<typeof onSave>[0] = {
			description: String(formData.get('description') ?? ''),
			checklistDescription: String(formData.get('checklistDescription') ?? ''),
			estimatedMinutes: formData.get('estimatedMinutes')
				? parseInt(String(formData.get('estimatedMinutes')))
				: null
		};
		if (variant === 'service') {
			updates.frequency = String(formData.get('frequency') ?? 'weekly');
		}
		onSave(updates);
	}
</script>

<div class="mb-2 rounded-lg border border-theme bg-theme p-3 last:mb-0">
	{#if isEditing}
		<!-- Edit Mode -->
		<form onsubmit={handleSubmit}>
			<div class="space-y-3">
				<div>
					<label for="task-desc-{task.id}" class="mb-1 block text-xs font-medium text-theme-muted"
						>Description</label
					>
					<input
						id="task-desc-{task.id}"
						type="text"
						name="description"
						value={task.description}
						class="w-full rounded border border-theme bg-theme-card px-2 py-1.5 text-sm text-theme focus:border-secondary-500 focus:outline-none"
						required
					/>
				</div>
				<div>
					<label
						for="task-checklist-{task.id}"
						class="mb-1 block text-xs font-medium text-theme-muted">Checklist Description</label
					>
					<input
						id="task-checklist-{task.id}"
						type="text"
						name="checklistDescription"
						value={task.checklistDescription ?? ''}
						class="w-full rounded border border-theme bg-theme-card px-2 py-1.5 text-sm text-theme focus:border-secondary-500 focus:outline-none"
						placeholder="Optional checklist text..."
					/>
				</div>
				{#if variant === 'service'}
					<div class="flex gap-3">
						<div class="flex-1">
							<label
								for="task-freq-{task.id}"
								class="mb-1 block text-xs font-medium text-theme-muted">Frequency</label
							>
							<select
								id="task-freq-{task.id}"
								name="frequency"
								class="w-full rounded border border-theme bg-theme-card px-2 py-1.5 text-sm text-theme focus:border-secondary-500 focus:outline-none"
							>
								<option value="daily" selected={task.frequency?.toLowerCase() === 'daily'}
									>Daily</option
								>
								<option
									value="weekly"
									selected={(task.frequency?.toLowerCase() ?? 'weekly') === 'weekly'}>Weekly</option
								>
								<option value="monthly" selected={task.frequency?.toLowerCase() === 'monthly'}
									>Monthly</option
								>
								<option value="quarterly" selected={task.frequency?.toLowerCase() === 'quarterly'}
									>Quarterly</option
								>
								<option value="triannual" selected={task.frequency?.toLowerCase() === 'triannual'}
									>3x/Year</option
								>
								<option value="annual" selected={task.frequency?.toLowerCase() === 'annual'}
									>Annual</option
								>
								<option value="as_needed" selected={task.frequency?.toLowerCase() === 'as_needed'}
									>As Needed</option
								>
							</select>
						</div>
						<div class="w-24">
							<label
								for="task-mins-{task.id}"
								class="mb-1 block text-xs font-medium text-theme-muted">Est. Min</label
							>
							<input
								id="task-mins-{task.id}"
								type="number"
								name="estimatedMinutes"
								value={task.estimatedMinutes ?? ''}
								min="0"
								class="w-full rounded border border-theme bg-theme-card px-2 py-1.5 text-sm text-theme focus:border-secondary-500 focus:outline-none"
								placeholder="—"
							/>
						</div>
					</div>
				{:else}
					<div>
						<label for="task-mins-{task.id}" class="mb-1 block text-xs font-medium text-theme-muted"
							>Est. Minutes</label
						>
						<input
							id="task-mins-{task.id}"
							type="number"
							name="estimatedMinutes"
							value={task.estimatedMinutes ?? ''}
							min="0"
							class="w-24 rounded border border-theme bg-theme-card px-2 py-1.5 text-sm text-theme focus:border-secondary-500 focus:outline-none"
							placeholder="—"
						/>
					</div>
				{/if}
				<div class="flex justify-end gap-2">
					<button
						type="button"
						onclick={onCancelEdit}
						class="rounded px-3 py-1 text-xs text-theme-muted hover:text-theme"
					>
						Cancel
					</button>
					<button
						type="submit"
						class="rounded bg-secondary-500 px-3 py-1 text-xs text-white hover:bg-secondary-600"
					>
						Save
					</button>
				</div>
			</div>
		</form>
	{:else}
		<!-- Display Mode -->
		<div class="flex items-start justify-between gap-2">
			<button
				type="button"
				class="flex flex-1 cursor-pointer items-start gap-2 text-left"
				onclick={onStartEdit}
			>
				<svg
					class="mt-0.5 h-4 w-4 shrink-0 text-theme-muted transition-transform"
					style="fill: none"
					viewBox="0 0 24 24"
					stroke="currentColor"
				>
					<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7" />
				</svg>
				<span class="flex-1">
					<span class="text-sm font-medium text-theme">
						{task.description}
					</span>
					{#if task.checklistDescription}
						<span class="mt-1 block text-xs text-theme-muted">
							{task.checklistDescription}
						</span>
					{/if}
					<span class="mt-2 flex flex-wrap gap-2">
						{#if variant === 'service' && task.frequency}
							<span
								class="rounded-full bg-primary-500/20 px-2 py-0.5 text-xs text-primary-600 dark:text-primary-400"
							>
								{formatFrequency(task.frequency)}
							</span>
						{/if}
						{#if task.estimatedMinutes}
							<span
								class="rounded-full bg-surface-100 px-2 py-0.5 text-xs text-surface-600 dark:bg-surface-700 dark:text-surface-300"
							>
								{task.estimatedMinutes} min
							</span>
						{/if}
					</span>
				</span>
			</button>
			<div class="flex items-center gap-1">
				{#if onMoveUp}
					<button
						type="button"
						onclick={(e) => {
							e.stopPropagation();
							onMoveUp?.();
						}}
						class="rounded p-1 text-theme-muted hover:bg-black/5 hover:text-theme dark:hover:bg-white/10"
						aria-label="Move task up"
					>
						<svg class="h-3 w-3" style="fill: none" viewBox="0 0 24 24" stroke="currentColor">
							<path
								stroke-linecap="round"
								stroke-linejoin="round"
								stroke-width="2"
								d="M5 15l7-7 7 7"
							/>
						</svg>
					</button>
				{/if}
				{#if onMoveDown}
					<button
						type="button"
						onclick={(e) => {
							e.stopPropagation();
							onMoveDown?.();
						}}
						class="rounded p-1 text-theme-muted hover:bg-black/5 hover:text-theme dark:hover:bg-white/10"
						aria-label="Move task down"
					>
						<svg class="h-3 w-3" style="fill: none" viewBox="0 0 24 24" stroke="currentColor">
							<path
								stroke-linecap="round"
								stroke-linejoin="round"
								stroke-width="2"
								d="M19 9l-7 7-7-7"
							/>
						</svg>
					</button>
				{/if}
				<button
					onclick={onDelete}
					class="rounded p-1 text-red-400 hover:bg-red-50 hover:text-red-500 dark:hover:bg-red-900/20"
					aria-label="Delete task"
				>
					<svg class="h-4 w-4" style="fill: none" viewBox="0 0 24 24" stroke="currentColor">
						<path
							stroke-linecap="round"
							stroke-linejoin="round"
							stroke-width="2"
							d="M6 18L18 6M6 6l12 12"
						/>
					</svg>
				</button>
			</div>
		</div>
	{/if}
</div>
