<script lang="ts">
	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 ActionGuard from '$lib/components/ActionGuard.svelte';

	const client = useConvexClient();

	// Queries
	const setoresQuery = useQuery(api.setores.list, {});

	// Estado do modal
	let showModal = $state(false);
	let editingSetor = $state<{
		_id: Id<'setores'>;
		nome: string;
		sigla: string;
	} | null>(null);

	// Estado do formulário
	let nome = $state('');
	let sigla = $state('');
	let isSubmitting = $state(false);
	let error = $state<string | null>(null);

	// Modal de confirmação de exclusão
	let showDeleteModal = $state(false);
	let setorToDelete = $state<{ _id: Id<'setores'>; nome: string } | null>(null);

	function openCreateModal() {
		editingSetor = null;
		nome = '';
		sigla = '';
		error = null;
		showModal = true;
	}

	function openEditModal(setor: { _id: Id<'setores'>; nome: string; sigla: string }) {
		editingSetor = setor;
		nome = setor.nome;
		sigla = setor.sigla;
		error = null;
		showModal = true;
	}

	function closeModal() {
		showModal = false;
		editingSetor = null;
		nome = '';
		sigla = '';
		error = null;
	}

	function openDeleteModal(setor: { _id: Id<'setores'>; nome: string }) {
		setorToDelete = setor;
		showDeleteModal = true;
	}

	function closeDeleteModal() {
		showDeleteModal = false;
		setorToDelete = null;
	}

	async function handleSubmit() {
		if (!nome.trim() || !sigla.trim()) {
			error = 'Nome e sigla são obrigatórios';
			return;
		}

		isSubmitting = true;
		error = null;

		try {
			if (editingSetor) {
				await client.mutation(api.setores.update, {
					id: editingSetor._id,
					nome: nome.trim(),
					sigla: sigla.trim().toUpperCase()
				});
			} else {
				await client.mutation(api.setores.create, {
					nome: nome.trim(),
					sigla: sigla.trim().toUpperCase()
				});
			}
			closeModal();
		} catch (e) {
			error = e instanceof Error ? e.message : 'Erro ao salvar setor';
		} finally {
			isSubmitting = false;
		}
	}

	async function handleDelete() {
		if (!setorToDelete) return;

		isSubmitting = true;
		error = null;

		try {
			await client.mutation(api.setores.remove, { id: setorToDelete._id });
			closeDeleteModal();
		} catch (e) {
			error = e instanceof Error ? e.message : 'Erro ao excluir setor';
		} finally {
			isSubmitting = false;
		}
	}

	function formatDate(timestamp: number): string {
		return new Date(timestamp).toLocaleDateString('pt-BR', {
			day: '2-digit',
			month: '2-digit',
			year: 'numeric',
			hour: '2-digit',
			minute: '2-digit'
		});
	}
</script>

<main class="mx-auto w-full max-w-7xl space-y-8 px-4 py-10">
	<!-- Header -->
	<section
		class="border-primary/25 from-primary/10 via-base-100 to-secondary/20 relative overflow-hidden rounded-3xl border bg-linear-to-br p-8 shadow-2xl"
	>
		<div class="bg-primary/20 absolute top-10 -left-10 h-40 w-40 rounded-full blur-3xl"></div>
		<div class="bg-secondary/20 absolute right-0 -bottom-16 h-56 w-56 rounded-full blur-3xl"></div>
		<div class="relative z-10 flex flex-col gap-6 lg:flex-row lg:items-center lg:justify-between">
			<div class="max-w-3xl space-y-4">
				<span
					class="border-primary/40 bg-primary/10 text-primary inline-flex w-fit items-center gap-2 rounded-full border px-4 py-1 text-xs font-semibold tracking-[0.28em] uppercase"
				>
					Configurações
				</span>
				<h1 class="text-base-content text-4xl leading-tight font-black sm:text-5xl">
					Gestão de Setores
				</h1>
				<p class="text-base-content/70 text-base leading-relaxed sm:text-lg">
					Gerencie os setores da organização. Setores são utilizados para organizar funcionários e
					definir responsabilidades em fluxos de trabalho.
				</p>
			</div>
			<div class="flex items-center gap-4">
				<ActionGuard recurso="setores" acao="criar">
					<button class="btn btn-primary shadow-lg" onclick={openCreateModal}>
						<svg
							xmlns="http://www.w3.org/2000/svg"
							class="h-5 w-5"
							fill="none"
							viewBox="0 0 24 24"
							stroke="currentColor"
						>
							<path
								stroke-linecap="round"
								stroke-linejoin="round"
								stroke-width="2"
								d="M12 4v16m8-8H4"
							/>
						</svg>
						Novo Setor
					</button>
				</ActionGuard>
			</div>
		</div>
	</section>

	<!-- Lista de Setores -->
	<section class="bg-base-100 rounded-2xl border p-6 shadow-lg">
		{#if setoresQuery.isLoading}
			<div class="flex items-center justify-center py-12">
				<span class="loading loading-spinner loading-lg text-primary"></span>
			</div>
		{:else if !setoresQuery.data || setoresQuery.data.length === 0}
			<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-16 w-16"
					fill="none"
					viewBox="0 0 24 24"
					stroke="currentColor"
				>
					<path
						stroke-linecap="round"
						stroke-linejoin="round"
						stroke-width="1.5"
						d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4"
					/>
				</svg>
				<h3 class="text-base-content/70 mt-4 text-lg font-semibold">Nenhum setor cadastrado</h3>
				<p class="text-base-content/50 mt-2">Clique em "Novo Setor" para criar o primeiro setor.</p>
			</div>
		{:else}
			<div class="overflow-x-auto">
				<table class="table w-full">
					<thead>
						<tr>
							<th>Sigla</th>
							<th>Nome</th>
							<th>Criado em</th>
							<th class="text-right">Ações</th>
						</tr>
					</thead>
					<tbody>
						{#each setoresQuery.data as setor (setor._id)}
							<tr class="hover">
								<td>
									<span class="badge badge-primary badge-lg font-mono font-bold">
										{setor.sigla}
									</span>
								</td>
								<td class="font-medium">{setor.nome}</td>
								<td class="text-base-content/60 text-sm">{formatDate(setor.createdAt)}</td>
								<td class="text-right">
									<div class="flex justify-end gap-2">
										<ActionGuard recurso="setores" acao="editar">
											<button
												class="btn btn-ghost btn-sm"
												onclick={() => openEditModal(setor)}
												aria-label="Editar setor {setor.nome}"
											>
												<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="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"
													/>
												</svg>
											</button>
										</ActionGuard>
										<ActionGuard recurso="setores" acao="excluir">
											<button
												class="btn btn-ghost btn-sm text-error"
												onclick={() => openDeleteModal(setor)}
												aria-label="Excluir setor {setor.nome}"
											>
												<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 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"
													/>
												</svg>
											</button>
										</ActionGuard>
									</div>
								</td>
							</tr>
						{/each}
					</tbody>
				</table>
			</div>
		{/if}
	</section>
</main>

<!-- Modal de Criação/Edição -->
{#if showModal}
	<div class="modal modal-open">
		<div class="modal-box">
			<h3 class="text-lg font-bold">
				{editingSetor ? 'Editar Setor' : 'Novo Setor'}
			</h3>

			{#if error}
				<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"
					>
						<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>{error}</span>
				</div>
			{/if}

			<form
				onsubmit={(e) => {
					e.preventDefault();
					handleSubmit();
				}}
				class="mt-4 space-y-4"
			>
				<div class="form-control">
					<label class="label" for="nome">
						<span class="label-text">Nome do Setor</span>
					</label>
					<input
						type="text"
						id="nome"
						bind:value={nome}
						class="input input-bordered w-full"
						placeholder="Ex: Tecnologia da Informação"
						required
					/>
				</div>

				<div class="form-control">
					<label class="label" for="sigla">
						<span class="label-text">Sigla</span>
					</label>
					<input
						type="text"
						id="sigla"
						bind:value={sigla}
						class="input input-bordered w-full uppercase"
						placeholder="Ex: TI"
						maxlength="10"
						required
					/>
					<p class="label">
						<span class="label-text-alt text-base-content/60">Máximo 10 caracteres</span>
					</p>
				</div>

				<div class="modal-action">
					<button type="button" class="btn" onclick={closeModal} disabled={isSubmitting}>
						Cancelar
					</button>
					<button type="submit" class="btn btn-primary" disabled={isSubmitting}>
						{#if isSubmitting}
							<span class="loading loading-spinner loading-sm"></span>
						{/if}
						{editingSetor ? 'Salvar' : 'Criar'}
					</button>
				</div>
			</form>
		</div>
		<button type="button" class="modal-backdrop" onclick={closeModal} aria-label="Fechar modal"
		></button>
	</div>
{/if}

<!-- Modal de Confirmação de Exclusão -->
{#if showDeleteModal && setorToDelete}
	<div class="modal modal-open">
		<div class="modal-box">
			<h3 class="text-error text-lg font-bold">Confirmar Exclusão</h3>

			{#if error}
				<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"
					>
						<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>{error}</span>
				</div>
			{/if}

			<p class="py-4">
				Tem certeza que deseja excluir o setor <strong>{setorToDelete.nome}</strong>?
			</p>
			<p class="text-base-content/60 text-sm">
				Esta ação não pode ser desfeita. Setores com funcionários ou passos de fluxo vinculados não
				podem ser excluídos.
			</p>

			<div class="modal-action">
				<button class="btn" onclick={closeDeleteModal} disabled={isSubmitting}> Cancelar </button>
				<button class="btn btn-error" onclick={handleDelete} disabled={isSubmitting}>
					{#if isSubmitting}
						<span class="loading loading-spinner loading-sm"></span>
					{/if}
					Excluir
				</button>
			</div>
		</div>
		<button
			type="button"
			class="modal-backdrop"
			onclick={closeDeleteModal}
			aria-label="Fechar modal"
		></button>
	</div>
{/if}
