<script lang="ts">
	import { page } from '$app/stores';
	import { resolve } from '$app/paths';
	import { useQuery, useConvexClient } from 'convex-svelte';
	import { api } from '@sgse-app/backend/convex/_generated/api';
	import type { Id } from '@sgse-app/backend/convex/_generated/dataModel';
	import { flip } from 'svelte/animate';

	const client = useConvexClient();
	const templateId = $derived($page.params.id as Id<'flowTemplates'>);

	// Queries
	const templateQuery = useQuery(api.flows.getTemplate, () => ({ id: templateId }));
	const stepsQuery = useQuery(api.flows.listStepsByTemplate, () => ({
		flowTemplateId: templateId
	}));
	const setoresQuery = useQuery(api.setores.list, {});

	// Query de sub-etapas (reativa baseada no step selecionado)
	const subEtapasQuery = useQuery(api.flows.listarSubEtapas, () =>
		selectedStepId ? { flowStepId: selectedStepId } : 'skip'
	);

	// Estado local para drag and drop
	let localSteps = $state<NonNullable<typeof stepsQuery.data>>([]);
	let isDragging = $state(false);

	// Sincronizar com query
	$effect(() => {
		if (stepsQuery.data && !isDragging) {
			localSteps = [...stepsQuery.data];
		}
	});

	// Estado do passo selecionado
	let selectedStepId = $state<Id<'flowSteps'> | null>(null);
	const selectedStep = $derived(localSteps?.find((s) => s._id === selectedStepId));

	// Modal de novo passo
	let showNewStepModal = $state(false);
	let newStepName = $state('');
	let newStepDescription = $state('');
	let newStepDuration = $state(1);
	let newStepSetorId = $state<Id<'setores'> | ''>('');
	let isCreatingStep = $state(false);
	let stepError = $state<string | null>(null);

	// Estado de edição
	let editingStep = $state<{
		name: string;
		description: string;
		expectedDuration: number;
		setorId: Id<'setores'>;
		requiredDocuments: string[];
	} | null>(null);
	let isSavingStep = $state(false);

	// Estado de sub-etapas
	let showSubEtapaModal = $state(false);
	let subEtapaNome = $state('');
	let subEtapaDescricao = $state('');
	let isCriandoSubEtapa = $state(false);
	let subEtapaError = $state<string | null>(null);

	// Inicializar edição quando selecionar passo
	$effect(() => {
		if (selectedStep) {
			editingStep = {
				name: selectedStep.name,
				description: selectedStep.description ?? '',
				expectedDuration: selectedStep.expectedDuration,
				setorId: selectedStep.setorId,
				requiredDocuments: selectedStep.requiredDocuments ?? []
			};
		} else {
			editingStep = null;
		}
	});

	function openNewStepModal() {
		newStepName = '';
		newStepDescription = '';
		newStepDuration = 1;
		newStepSetorId = setoresQuery.data?.[0]?._id ?? '';
		stepError = null;
		showNewStepModal = true;
	}

	function closeNewStepModal() {
		showNewStepModal = false;
	}

	async function handleCreateStep() {
		if (!newStepName.trim()) {
			stepError = 'O nome é obrigatório';
			return;
		}
		if (!newStepSetorId) {
			stepError = 'Selecione um setor';
			return;
		}

		isCreatingStep = true;
		stepError = null;

		try {
			await client.mutation(api.flows.createStep, {
				flowTemplateId: templateId,
				name: newStepName.trim(),
				description: newStepDescription.trim() || undefined,
				expectedDuration: newStepDuration,
				setorId: newStepSetorId as Id<'setores'>
			});
			closeNewStepModal();
		} catch (e) {
			stepError = e instanceof Error ? e.message : 'Erro ao criar passo';
		} finally {
			isCreatingStep = false;
		}
	}

	async function handleSaveStep() {
		if (!selectedStepId || !editingStep) return;

		isSavingStep = true;

		try {
			await client.mutation(api.flows.updateStep, {
				id: selectedStepId,
				name: editingStep.name,
				description: editingStep.description || undefined,
				expectedDuration: editingStep.expectedDuration,
				setorId: editingStep.setorId,
				requiredDocuments:
					editingStep.requiredDocuments.length > 0 ? editingStep.requiredDocuments : undefined
			});
		} catch (e) {
			console.error('Erro ao salvar passo:', e);
		} finally {
			isSavingStep = false;
		}
	}

	async function handleDeleteStep() {
		if (!selectedStepId) return;

		try {
			await client.mutation(api.flows.deleteStep, { id: selectedStepId });
			selectedStepId = null;
		} catch (e) {
			console.error('Erro ao excluir passo:', e);
		}
	}

	async function moveStepUp(index: number) {
		if (index === 0 || !localSteps) return;

		const previousSteps = [...localSteps];
		const newSteps = [...localSteps];
		[newSteps[index - 1], newSteps[index]] = [newSteps[index], newSteps[index - 1]];
		localSteps = newSteps;
		isDragging = true;

		const stepIds = newSteps.map((s) => s._id);
		try {
			await client.mutation(api.flows.reorderSteps, {
				flowTemplateId: templateId,
				stepIds
			});
		} catch (err) {
			console.error('Erro ao reordenar passos:', err);
			// Reverter em caso de erro
			localSteps = previousSteps;
		} finally {
			isDragging = false;
		}
	}

	async function moveStepDown(index: number) {
		if (!localSteps || index === localSteps.length - 1) return;

		const previousSteps = [...localSteps];
		const newSteps = [...localSteps];
		[newSteps[index], newSteps[index + 1]] = [newSteps[index + 1], newSteps[index]];
		localSteps = newSteps;
		isDragging = true;

		const stepIds = newSteps.map((s) => s._id);
		try {
			await client.mutation(api.flows.reorderSteps, {
				flowTemplateId: templateId,
				stepIds
			});
		} catch (err) {
			console.error('Erro ao reordenar passos:', err);
			// Reverter em caso de erro
			localSteps = previousSteps;
		} finally {
			isDragging = false;
		}
	}

	async function handlePublish() {
		try {
			await client.mutation(api.flows.updateTemplate, {
				id: templateId,
				status: 'published'
			});
		} catch (e) {
			console.error('Erro ao publicar:', e);
		}
	}

	function addRequiredDocument() {
		if (editingStep) {
			editingStep.requiredDocuments = [...editingStep.requiredDocuments, ''];
		}
	}

	function removeRequiredDocument(index: number) {
		if (editingStep) {
			editingStep.requiredDocuments = editingStep.requiredDocuments.filter((_, i) => i !== index);
		}
	}

	function updateRequiredDocument(index: number, value: string) {
		if (editingStep) {
			editingStep.requiredDocuments = editingStep.requiredDocuments.map((doc, i) =>
				i === index ? value : doc
			);
		}
	}

	// Funções de sub-etapas
	function openSubEtapaModal() {
		subEtapaNome = '';
		subEtapaDescricao = '';
		subEtapaError = null;
		showSubEtapaModal = true;
	}

	function closeSubEtapaModal() {
		showSubEtapaModal = false;
		subEtapaNome = '';
		subEtapaDescricao = '';
		subEtapaError = null;
	}

	async function handleCriarSubEtapa() {
		if (!selectedStepId || !subEtapaNome.trim()) {
			subEtapaError = 'O nome é obrigatório';
			return;
		}

		isCriandoSubEtapa = true;
		subEtapaError = null;

		try {
			await client.mutation(api.flows.criarSubEtapa, {
				flowStepId: selectedStepId,
				name: subEtapaNome.trim(),
				description: subEtapaDescricao.trim() || undefined
			});
			closeSubEtapaModal();
		} catch (e) {
			subEtapaError = e instanceof Error ? e.message : 'Erro ao criar sub-etapa';
		} finally {
			isCriandoSubEtapa = false;
		}
	}

	async function handleDeletarSubEtapa(subEtapaId: Id<'flowSubSteps'>) {
		if (!confirm('Tem certeza que deseja excluir esta sub-etapa?')) {
			return;
		}

		try {
			await client.mutation(api.flows.deletarSubEtapa, { subEtapaId });
		} catch (e) {
			alert(e instanceof Error ? e.message : 'Erro ao deletar sub-etapa');
		}
	}

	async function handleAtualizarStatusSubEtapa(
		subEtapaId: Id<'flowSubSteps'>,
		novoStatus: 'pending' | 'in_progress' | 'completed' | 'blocked'
	) {
		try {
			await client.mutation(api.flows.atualizarSubEtapa, {
				subEtapaId,
				status: novoStatus
			});
		} catch (e) {
			alert(e instanceof Error ? e.message : 'Erro ao atualizar status');
		}
	}
</script>

<main class="flex h-[calc(100vh-4rem)] flex-col">
	<!-- Header -->
	<header class="bg-base-100 border-b px-6 py-4">
		<div class="flex items-center justify-between">
			<div class="flex items-center gap-4">
				<a href={resolve('/(dashboard)/fluxos')} class="btn btn-ghost btn-sm">
					<svg
						xmlns="http://www.w3.org/2000/svg"
						class="h-5 w-5"
						fill="none"
						viewBox="0 0 24 24"
						stroke="currentColor"
						aria-hidden="true"
					>
						<path
							stroke-linecap="round"
							stroke-linejoin="round"
							stroke-width="2"
							d="M10 19l-7-7m0 0l7-7m-7 7h18"
						/>
					</svg>
					Voltar
				</a>
				<div>
					{#if templateQuery.isLoading}
						<div class="bg-base-300 h-6 w-48 animate-pulse rounded"></div>
					{:else if templateQuery.data}
						<h1 class="text-xl font-bold">{templateQuery.data.name}</h1>
						<p class="text-base-content/60 text-sm">
							{templateQuery.data.description ?? 'Sem descrição'}
						</p>
					{/if}
				</div>
			</div>

			<div class="flex items-center gap-2">
				{#if templateQuery.data?.status === 'draft'}
					<button
						class="btn btn-success btn-sm"
						onclick={handlePublish}
						disabled={!localSteps || localSteps.length === 0}
					>
						<svg
							xmlns="http://www.w3.org/2000/svg"
							class="h-4 w-4"
							fill="none"
							viewBox="0 0 24 24"
							stroke="currentColor"
							aria-hidden="true"
						>
							<path
								stroke-linecap="round"
								stroke-linejoin="round"
								stroke-width="2"
								d="M5 13l4 4L19 7"
							/>
						</svg>
						Publicar
					</button>
				{:else if templateQuery.data?.status === 'published'}
					<span class="badge badge-success">Publicado</span>
				{:else if templateQuery.data?.status === 'archived'}
					<span class="badge badge-neutral">Arquivado</span>
				{/if}
			</div>
		</div>
	</header>

	<!-- Conteúdo Principal -->
	<div class="flex flex-1 overflow-hidden">
		<!-- Lista de Passos (Kanban) -->
		<div class="flex-1 overflow-auto p-6">
			<div class="mb-4 flex items-center justify-between">
				<h2 class="text-lg font-semibold">Passos do Fluxo</h2>
				<button class="btn btn-secondary btn-sm" onclick={openNewStepModal}>
					<svg
						xmlns="http://www.w3.org/2000/svg"
						class="h-4 w-4"
						fill="none"
						viewBox="0 0 24 24"
						stroke="currentColor"
						aria-hidden="true"
					>
						<path
							stroke-linecap="round"
							stroke-linejoin="round"
							stroke-width="2"
							d="M12 4v16m8-8H4"
						/>
					</svg>
					Novo Passo
				</button>
			</div>

			{#if stepsQuery.isLoading}
				<div class="flex items-center justify-center py-12">
					<span class="loading loading-spinner loading-lg text-secondary"></span>
				</div>
			{:else if !localSteps || localSteps.length === 0}
				<div
					class="flex flex-col items-center justify-center rounded-xl border-2 border-dashed py-12 text-center"
				>
					<svg
						xmlns="http://www.w3.org/2000/svg"
						class="text-base-content/30 h-12 w-12"
						fill="none"
						viewBox="0 0 24 24"
						stroke="currentColor"
						aria-hidden="true"
					>
						<path
							stroke-linecap="round"
							stroke-linejoin="round"
							stroke-width="1.5"
							d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"
						/>
					</svg>
					<p class="text-base-content/60 mt-4">Nenhum passo definido</p>
					<p class="text-base-content/40 text-sm">
						Clique em "Novo Passo" para adicionar o primeiro passo
					</p>
				</div>
			{:else if localSteps && localSteps.length > 0}
				<div class="space-y-3">
					{#each localSteps as step, index (step._id)}
						<div
							class="card w-full border text-left transition-all duration-200 {selectedStepId ===
							step._id
								? 'border-secondary bg-secondary/10 ring-secondary ring-2'
								: 'bg-base-100 hover:bg-base-200'}"
							animate:flip={{ duration: 200 }}
						>
							<div class="card-body p-4">
								<div class="flex items-start gap-3">
									<div
										class="bg-secondary/20 text-secondary flex h-8 w-8 shrink-0 items-center justify-center rounded-full text-sm font-bold"
									>
										{index + 1}
									</div>
									<div
										class="min-w-0 flex-1 cursor-pointer"
										onclick={() => (selectedStepId = step._id)}
										onkeydown={(e) => {
											if (e.key === 'Enter' || e.key === ' ') {
												e.preventDefault();
												selectedStepId = step._id;
											}
										}}
										role="button"
										tabindex="0"
									>
										<h3 class="font-semibold">{step.name}</h3>
										{#if step.description}
											<p class="text-base-content/60 mt-1 truncate text-sm">{step.description}</p>
										{/if}
										<div class="text-base-content/50 mt-2 flex flex-wrap gap-3 text-xs">
											<span class="flex items-center gap-1">
												<svg
													xmlns="http://www.w3.org/2000/svg"
													class="h-3 w-3"
													fill="none"
													viewBox="0 0 24 24"
													stroke="currentColor"
													aria-hidden="true"
												>
													<path
														stroke-linecap="round"
														stroke-linejoin="round"
														stroke-width="2"
														d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5"
													/>
												</svg>
												{step.setorNome ?? 'Setor não definido'}
											</span>
											<span class="flex items-center gap-1">
												<svg
													xmlns="http://www.w3.org/2000/svg"
													class="h-3 w-3"
													fill="none"
													viewBox="0 0 24 24"
													stroke="currentColor"
													aria-hidden="true"
												>
													<path
														stroke-linecap="round"
														stroke-linejoin="round"
														stroke-width="2"
														d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"
													/>
												</svg>
												{step.expectedDuration} dia{step.expectedDuration > 1 ? 's' : ''}
											</span>
										</div>
									</div>
									<div class="flex flex-col gap-1">
										<button
											type="button"
											class="btn btn-ghost btn-xs"
											onclick={() => moveStepUp(index)}
											disabled={index === 0 || isDragging}
											aria-label="Mover passo para cima"
										>
											<svg
												xmlns="http://www.w3.org/2000/svg"
												class="h-4 w-4"
												fill="none"
												viewBox="0 0 24 24"
												stroke="currentColor"
												aria-hidden="true"
											>
												<path
													stroke-linecap="round"
													stroke-linejoin="round"
													stroke-width="2"
													d="M5 15l7-7 7 7"
												/>
											</svg>
										</button>
										<button
											type="button"
											class="btn btn-ghost btn-xs"
											onclick={() => moveStepDown(index)}
											disabled={index === localSteps.length - 1 || isDragging}
											aria-label="Mover passo para baixo"
										>
											<svg
												xmlns="http://www.w3.org/2000/svg"
												class="h-4 w-4"
												fill="none"
												viewBox="0 0 24 24"
												stroke="currentColor"
												aria-hidden="true"
											>
												<path
													stroke-linecap="round"
													stroke-linejoin="round"
													stroke-width="2"
													d="M19 9l-7 7-7-7"
												/>
											</svg>
										</button>
									</div>
								</div>
							</div>
						</div>
					{/each}
				</div>
			{/if}
		</div>

		<!-- Sidebar de Edição -->
		<aside class="bg-base-200 w-96 shrink-0 overflow-auto border-l p-6">
			{#if selectedStep && editingStep}
				<div class="space-y-6">
					<div class="flex items-center justify-between">
						<h3 class="text-lg font-semibold">Editar Passo</h3>
						<button
							class="btn btn-ghost btn-sm"
							onclick={() => (selectedStepId = null)}
							aria-label="Fechar edição"
						>
							<svg
								xmlns="http://www.w3.org/2000/svg"
								class="h-5 w-5"
								fill="none"
								viewBox="0 0 24 24"
								stroke="currentColor"
								aria-hidden="true"
							>
								<path
									stroke-linecap="round"
									stroke-linejoin="round"
									stroke-width="2"
									d="M6 18L18 6M6 6l12 12"
								/>
							</svg>
						</button>
					</div>

					<div class="form-control">
						<label class="label" for="step-name">
							<span class="label-text">Nome</span>
						</label>
						<input
							type="text"
							id="step-name"
							bind:value={editingStep.name}
							class="input input-bordered w-full"
						/>
					</div>

					<div class="form-control">
						<label class="label" for="step-description">
							<span class="label-text">Descrição</span>
						</label>
						<textarea
							id="step-description"
							bind:value={editingStep.description}
							class="textarea textarea-bordered w-full"
							rows="3"
						></textarea>
					</div>

					<div class="form-control">
						<label class="label" for="step-duration">
							<span class="label-text">Duração Esperada (dias)</span>
						</label>
						<input
							type="number"
							id="step-duration"
							bind:value={editingStep.expectedDuration}
							class="input input-bordered w-full"
							min="1"
						/>
					</div>

					<div class="form-control">
						<label class="label" for="step-setor">
							<span class="label-text">Setor Responsável</span>
						</label>
						<select
							id="step-setor"
							bind:value={editingStep.setorId}
							class="select select-bordered w-full"
						>
							{#if setoresQuery.data}
								{#each setoresQuery.data as setor (setor._id)}
									<option value={setor._id}>{setor.nome} ({setor.sigla})</option>
								{/each}
							{/if}
						</select>
					</div>

					<div class="form-control">
						<span class="label">
							<span class="label-text">Documentos Obrigatórios</span>
						</span>
						<div class="space-y-2">
							{#each editingStep.requiredDocuments as doc, index (index)}
								<div class="flex gap-2">
									<input
										type="text"
										value={doc}
										oninput={(e) => updateRequiredDocument(index, e.currentTarget.value)}
										class="input input-bordered input-sm flex-1"
										placeholder="Nome do documento"
									/>
									<button
										type="button"
										class="btn btn-ghost btn-sm text-error"
										onclick={() => removeRequiredDocument(index)}
										aria-label="Remover documento"
									>
										<svg
											xmlns="http://www.w3.org/2000/svg"
											class="h-4 w-4"
											fill="none"
											viewBox="0 0 24 24"
											stroke="currentColor"
											aria-hidden="true"
										>
											<path
												stroke-linecap="round"
												stroke-linejoin="round"
												stroke-width="2"
												d="M6 18L18 6M6 6l12 12"
											/>
										</svg>
									</button>
								</div>
							{/each}
							<button
								type="button"
								class="btn btn-ghost btn-sm w-full"
								onclick={addRequiredDocument}
							>
								<svg
									xmlns="http://www.w3.org/2000/svg"
									class="h-4 w-4"
									fill="none"
									viewBox="0 0 24 24"
									stroke="currentColor"
									aria-hidden="true"
								>
									<path
										stroke-linecap="round"
										stroke-linejoin="round"
										stroke-width="2"
										d="M12 4v16m8-8H4"
									/>
								</svg>
								Adicionar Documento
							</button>
						</div>
					</div>

					<!-- Sub-etapas -->
					<div class="form-control">
						<div class="label">
							<span class="label-text font-semibold">Sub-etapas</span>
							<button
								type="button"
								class="btn btn-ghost btn-xs"
								onclick={openSubEtapaModal}
								aria-label="Adicionar sub-etapa"
							>
								<svg
									xmlns="http://www.w3.org/2000/svg"
									class="h-4 w-4"
									fill="none"
									viewBox="0 0 24 24"
									stroke="currentColor"
									aria-hidden="true"
								>
									<path
										stroke-linecap="round"
										stroke-linejoin="round"
										stroke-width="2"
										d="M12 4v16m8-8H4"
									/>
								</svg>
								Adicionar
							</button>
						</div>
						<div class="space-y-2">
							{#if subEtapasQuery.isLoading}
								<div class="flex items-center justify-center py-4">
									<span class="loading loading-spinner loading-sm"></span>
								</div>
							{:else if subEtapasQuery.data && subEtapasQuery.data.length > 0}
								{#each subEtapasQuery.data as subEtapa (subEtapa._id)}
									<div
										class="border-base-300 bg-base-100 flex items-center gap-2 rounded-lg border p-2"
									>
										<div class="flex-1">
											<div class="text-sm font-medium">{subEtapa.name}</div>
											{#if subEtapa.description}
												<div class="text-base-content/60 text-xs">{subEtapa.description}</div>
											{/if}
											<div class="mt-1">
												<span
													class="badge badge-xs {subEtapa.status === 'completed'
														? 'badge-success'
														: subEtapa.status === 'in_progress'
															? 'badge-info'
															: subEtapa.status === 'blocked'
																? 'badge-error'
																: 'badge-ghost'}"
												>
													{subEtapa.status === 'completed'
														? 'Concluída'
														: subEtapa.status === 'in_progress'
															? 'Em Andamento'
															: subEtapa.status === 'blocked'
																? 'Bloqueada'
																: 'Pendente'}
												</span>
											</div>
										</div>
										<div class="flex gap-1">
											<select
												class="select select-xs select-bordered"
												value={subEtapa.status}
												onchange={(e) =>
													handleAtualizarStatusSubEtapa(
														subEtapa._id,
														e.currentTarget.value as
															| 'pending'
															| 'in_progress'
															| 'completed'
															| 'blocked'
													)}
											>
												<option value="pending">Pendente</option>
												<option value="in_progress">Em Andamento</option>
												<option value="completed">Concluída</option>
												<option value="blocked">Bloqueada</option>
											</select>
											<button
												type="button"
												class="btn btn-ghost btn-xs text-error"
												onclick={() => handleDeletarSubEtapa(subEtapa._id)}
												aria-label="Deletar sub-etapa"
											>
												<svg
													xmlns="http://www.w3.org/2000/svg"
													class="h-4 w-4"
													fill="none"
													viewBox="0 0 24 24"
													stroke="currentColor"
													aria-hidden="true"
												>
													<path
														stroke-linecap="round"
														stroke-linejoin="round"
														stroke-width="2"
														d="M6 18L18 6M6 6l12 12"
													/>
												</svg>
											</button>
										</div>
									</div>
								{/each}
							{:else}
								<div
									class="text-base-content/40 border-base-300 bg-base-200/50 rounded-lg border border-dashed p-4 text-center text-sm"
								>
									Nenhuma sub-etapa adicionada
								</div>
							{/if}
						</div>
					</div>

					<div class="flex gap-2 pt-4">
						<button class="btn btn-error btn-outline flex-1" onclick={handleDeleteStep}>
							Excluir
						</button>
						<button
							class="btn btn-secondary flex-1"
							onclick={handleSaveStep}
							disabled={isSavingStep}
						>
							{#if isSavingStep}
								<span class="loading loading-spinner loading-sm"></span>
							{/if}
							Salvar
						</button>
					</div>
				</div>
			{:else}
				<div class="flex flex-col items-center justify-center py-12 text-center">
					<svg
						xmlns="http://www.w3.org/2000/svg"
						class="text-base-content/30 h-12 w-12"
						fill="none"
						viewBox="0 0 24 24"
						stroke="currentColor"
						aria-hidden="true"
					>
						<path
							stroke-linecap="round"
							stroke-linejoin="round"
							stroke-width="1.5"
							d="M15 15l-2 5L9 9l11 4-5 2zm0 0l5 5M7.188 2.239l.777 2.897M5.136 7.965l-2.898-.777M13.95 4.05l-2.122 2.122m-5.657 5.656l-2.12 2.122"
						/>
					</svg>
					<p class="text-base-content/60 mt-4">Selecione um passo</p>
					<p class="text-base-content/40 text-sm">Clique em um passo para editar seus detalhes</p>
				</div>
			{/if}
		</aside>
	</div>
</main>

<!-- Modal de Novo Passo -->
{#if showNewStepModal}
	<div class="modal modal-open">
		<div class="modal-box">
			<h3 class="text-lg font-bold">Novo Passo</h3>

			{#if stepError}
				<div class="alert alert-error mt-4">
					<svg
						xmlns="http://www.w3.org/2000/svg"
						class="h-6 w-6 shrink-0 stroke-current"
						fill="none"
						viewBox="0 0 24 24"
						aria-hidden="true"
					>
						<path
							stroke-linecap="round"
							stroke-linejoin="round"
							stroke-width="2"
							d="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z"
						/>
					</svg>
					<span>{stepError}</span>
				</div>
			{/if}

			<form
				onsubmit={(e) => {
					e.preventDefault();
					handleCreateStep();
				}}
				class="mt-4 space-y-4"
			>
				<div class="form-control">
					<label class="label" for="new-step-name">
						<span class="label-text">Nome do Passo</span>
					</label>
					<input
						type="text"
						id="new-step-name"
						bind:value={newStepName}
						class="input input-bordered w-full"
						placeholder="Ex: Análise Jurídica"
						required
					/>
				</div>

				<div class="form-control">
					<label class="label" for="new-step-description">
						<span class="label-text">Descrição (opcional)</span>
					</label>
					<textarea
						id="new-step-description"
						bind:value={newStepDescription}
						class="textarea textarea-bordered w-full"
						placeholder="Descreva o que deve ser feito neste passo..."
						rows="2"
					></textarea>
				</div>

				<div class="form-control">
					<label class="label" for="new-step-duration">
						<span class="label-text">Duração Esperada (dias)</span>
					</label>
					<input
						type="number"
						id="new-step-duration"
						bind:value={newStepDuration}
						class="input input-bordered w-full"
						min="1"
						required
					/>
				</div>

				<div class="form-control">
					<label class="label" for="new-step-setor">
						<span class="label-text">Setor Responsável</span>
					</label>
					<select
						id="new-step-setor"
						bind:value={newStepSetorId}
						class="select select-bordered w-full"
						required
					>
						<option value="">Selecione um setor</option>
						{#if setoresQuery.data}
							{#each setoresQuery.data as setor (setor._id)}
								<option value={setor._id}>{setor.nome} ({setor.sigla})</option>
							{/each}
						{/if}
					</select>
				</div>

				<div class="modal-action">
					<button type="button" class="btn" onclick={closeNewStepModal} disabled={isCreatingStep}>
						Cancelar
					</button>
					<button type="submit" class="btn btn-secondary" disabled={isCreatingStep}>
						{#if isCreatingStep}
							<span class="loading loading-spinner loading-sm"></span>
						{/if}
						Criar Passo
					</button>
				</div>
			</form>
		</div>
		<button
			type="button"
			class="modal-backdrop"
			onclick={closeNewStepModal}
			aria-label="Fechar modal"
		></button>
	</div>
{/if}

<!-- Modal de Nova Sub-etapa -->
{#if showSubEtapaModal}
	<div class="modal modal-open">
		<div class="modal-box">
			<h3 class="text-lg font-bold">Nova Sub-etapa</h3>

			{#if subEtapaError}
				<div class="alert alert-error mt-4">
					<svg
						xmlns="http://www.w3.org/2000/svg"
						class="h-6 w-6 shrink-0 stroke-current"
						fill="none"
						viewBox="0 0 24 24"
						aria-hidden="true"
					>
						<path
							stroke-linecap="round"
							stroke-linejoin="round"
							stroke-width="2"
							d="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z"
						/>
					</svg>
					<span>{subEtapaError}</span>
				</div>
			{/if}

			<form
				onsubmit={(e) => {
					e.preventDefault();
					handleCriarSubEtapa();
				}}
				class="mt-4 space-y-4"
			>
				<div class="form-control">
					<label class="label" for="sub-etapa-nome">
						<span class="label-text">Nome da Sub-etapa</span>
					</label>
					<input
						type="text"
						id="sub-etapa-nome"
						bind:value={subEtapaNome}
						class="input input-bordered w-full"
						placeholder="Ex: Revisar documentação"
						required
					/>
				</div>

				<div class="form-control">
					<label class="label" for="sub-etapa-descricao">
						<span class="label-text">Descrição (opcional)</span>
					</label>
					<textarea
						id="sub-etapa-descricao"
						bind:value={subEtapaDescricao}
						class="textarea textarea-bordered w-full"
						placeholder="Descreva a sub-etapa..."
						rows="2"
					></textarea>
				</div>

				<div class="modal-action">
					<button
						type="button"
						class="btn"
						onclick={closeSubEtapaModal}
						disabled={isCriandoSubEtapa}
					>
						Cancelar
					</button>
					<button type="submit" class="btn btn-secondary" disabled={isCriandoSubEtapa}>
						{#if isCriandoSubEtapa}
							<span class="loading loading-spinner loading-sm"></span>
						{/if}
						Criar Sub-etapa
					</button>
				</div>
			</form>
		</div>
		<button
			type="button"
			class="modal-backdrop"
			onclick={closeSubEtapaModal}
			aria-label="Fechar modal"
		></button>
	</div>
{/if}
