<script lang="ts">
	import { useConvexClient } from 'convex-svelte';
	import { api } from '@sgse-app/backend/convex/_generated/api';
	import { goto } from '$app/navigation';
	import { resolve } from '$app/paths';
	import { onMount } from 'svelte';
	import {
		Home,
		Trash2,
		ArrowLeft,
		CheckCircle,
		XCircle,
		X,
		Filter,
		Users,
		Inbox,
		Search,
		AlertTriangle,
		User
	} from 'lucide-svelte';

	const client = useConvexClient();

	let list: Array<any> = $state([]);
	let filtro = $state('');
	let notice: { kind: 'success' | 'error'; text: string } | null = $state(null);
	let toDelete: { id: string; nome: string; cpf: string; matricula: string } | null = $state(null);
	let deletingId: string | null = $state(null);

	async function load() {
		try {
			list = await client.query(api.funcionarios.getAll, {} as any);
		} catch (e) {
			notice = { kind: 'error', text: 'Falha ao carregar funcionários.' };
		}
	}

	function openDeleteModal(id: string, nome: string, cpf: string, matricula: string) {
		toDelete = { id, nome, cpf, matricula };
		(document.getElementById('delete_modal_func_excluir') as HTMLDialogElement)?.showModal();
	}

	function closeDeleteModal() {
		toDelete = null;
		(document.getElementById('delete_modal_func_excluir') as HTMLDialogElement)?.close();
	}

	async function confirmDelete() {
		if (!toDelete) return;
		try {
			deletingId = toDelete.id;
			await client.mutation(api.funcionarios.remove, { id: toDelete.id } as any);
			closeDeleteModal();
			notice = { kind: 'success', text: `Funcionário "${toDelete.nome}" excluído com sucesso!` };
			await load();

			// Auto-fechar mensagem de sucesso após 5 segundos
			setTimeout(() => {
				notice = null;
			}, 5000);
		} catch (e) {
			notice = { kind: 'error', text: 'Erro ao excluir cadastro. Tente novamente.' };
		} finally {
			deletingId = null;
		}
	}

	function limparFiltro() {
		filtro = '';
	}

	function back() {
		goto(resolve('/recursos-humanos/funcionarios'));
	}

	// Computed para lista filtrada
	const filtered = $derived(
		list.filter((f) => {
			const q = (filtro || '').toLowerCase();
			return (
				!q ||
				(f.nome || '').toLowerCase().includes(q) ||
				(f.cpf || '').includes(q) ||
				(f.matricula || '').toLowerCase().includes(q)
			);
		})
	);

	onMount(() => {
		void load();
	});
</script>

<!-- Breadcrumb -->
<div class="breadcrumbs mb-4 text-sm">
	<ul>
		<li>
			<a href={resolve('/')} class="text-primary hover:text-primary-focus">
				<Home class="h-4 w-4" strokeWidth={2} />
				Dashboard
			</a>
		</li>
		<li>
			<a href={resolve('/recursos-humanos')} class="text-primary hover:text-primary-focus"
				>Recursos Humanos</a
			>
		</li>
		<li>
			<a
				href={resolve('/recursos-humanos/funcionarios')}
				class="text-primary hover:text-primary-focus">Funcionários</a
			>
		</li>
		<li class="font-semibold">Excluir Funcionários</li>
	</ul>
</div>

<!-- Header com ícone e descrição -->
<div class="mb-6">
	<div class="mb-2 flex items-center gap-3">
		<div class="bg-error/10 rounded-xl p-3">
			<Trash2 class="text-error h-8 w-8" strokeWidth={2} />
		</div>
		<div class="flex-1">
			<h1 class="text-base-content text-3xl font-bold">Excluir Funcionários</h1>
			<p class="text-base-content/60 mt-1">Selecione o funcionário que deseja remover do sistema</p>
		</div>
		<button class="btn gap-2" onclick={back}>
			<ArrowLeft class="h-5 w-5" strokeWidth={2} />
			Voltar
		</button>
	</div>
</div>

<!-- Alerta de sucesso/erro -->
{#if notice}
	<div
		class="alert mb-6 shadow-lg"
		class:alert-success={notice.kind === 'success'}
		class:alert-error={notice.kind === 'error'}
	>
		{#if notice.kind === 'success'}
			<CheckCircle class="h-6 w-6 shrink-0 stroke-current" strokeWidth={2} />
		{:else}
			<XCircle class="h-6 w-6 shrink-0 stroke-current" strokeWidth={2} />
		{/if}
		<span class="font-semibold">{notice.text}</span>
		<button class="btn btn-sm btn-ghost" onclick={() => (notice = null)} aria-label="Fechar alerta">
			<X class="h-4 w-4" strokeWidth={2} />
		</button>
	</div>
{/if}

<!-- Card de Filtros -->
<div class="card bg-base-100 mb-6 shadow-xl">
	<div class="card-body">
		<div class="mb-4 flex items-center justify-between">
			<h2 class="card-title text-lg">
				<Filter class="text-primary h-5 w-5" strokeWidth={2} />
				Filtros de Busca
			</h2>
			{#if filtro}
				<button class="btn btn-sm btn-ghost gap-2" onclick={limparFiltro}>
					<X class="h-4 w-4" strokeWidth={2} />
					Limpar Filtros
				</button>
			{/if}
		</div>

		<div class="form-control w-full">
			<label class="label" for="func_excluir_busca">
				<span class="label-text font-semibold">Buscar por Nome, CPF ou Matrícula</span>
			</label>
			<input
				id="func_excluir_busca"
				type="text"
				placeholder="Digite para filtrar..."
				class="input input-bordered input-primary focus:input-primary w-full"
				bind:value={filtro}
			/>
			<div class="label">
				<span class="label-text-alt text-base-content/60">
					{filtered.length} funcionário{filtered.length !== 1 ? 's' : ''} encontrado{filtered.length !==
					1
						? 's'
						: ''}
				</span>
			</div>
		</div>
	</div>
</div>

<!-- Tabela de Funcionários -->
<div class="card bg-base-100 shadow-xl">
	<div class="card-body">
		<h2 class="card-title mb-4 text-lg">
			<Users class="text-primary h-5 w-5" strokeWidth={2} />
			Lista de Funcionários
		</h2>

		{#if list.length === 0}
			<div class="flex flex-col items-center justify-center py-12 text-center">
				<div class="bg-base-200 mb-4 rounded-full p-4">
					<Inbox class="text-base-content/30 h-12 w-12" strokeWidth={2} />
				</div>
				<p class="text-base-content/70 text-lg font-semibold">Nenhum funcionário cadastrado</p>
				<p class="text-base-content/50 mt-2 text-sm">
					Cadastre funcionários para gerenciá-los aqui
				</p>
			</div>
		{:else if filtered.length === 0}
			<div class="flex flex-col items-center justify-center py-12 text-center">
				<div class="bg-base-200 mb-4 rounded-full p-4">
					<Search class="text-base-content/30 h-12 w-12" strokeWidth={2} />
				</div>
				<p class="text-base-content/70 text-lg font-semibold">Nenhum resultado encontrado</p>
				<p class="text-base-content/50 mt-2 text-sm">Tente ajustar os filtros de busca</p>
				<button class="btn btn-primary btn-sm mt-4" onclick={limparFiltro}>Limpar Filtros</button>
			</div>
		{:else}
			<div class="overflow-x-auto">
				<table class="table-zebra table">
					<thead class="bg-base-200 sticky top-0 z-10">
						<tr>
							<th class="text-base">Nome</th>
							<th class="text-base">CPF</th>
							<th class="text-base">Matrícula</th>
							<th class="text-center text-base">Ações</th>
						</tr>
					</thead>
					<tbody>
						{#each filtered as f}
							<tr class="hover">
								<td class="font-semibold">{f.nome}</td>
								<td>{f.cpf}</td>
								<td><span class="badge badge-ghost">{f.matricula}</span></td>
								<td class="text-center">
									<button
										class="btn btn-error btn-sm gap-2"
										onclick={() => openDeleteModal(f._id, f.nome, f.cpf, f.matricula)}
									>
										<Trash2 class="h-4 w-4" strokeWidth={2} />
										Excluir
									</button>
								</td>
							</tr>
						{/each}
					</tbody>
				</table>
			</div>
		{/if}
	</div>
</div>

<!-- Modal de Confirmação de Exclusão -->
<dialog id="delete_modal_func_excluir" class="modal">
	<div class="modal-box max-w-md">
		<h3 class="text-error mb-4 flex items-center gap-2 text-2xl font-bold">
			<AlertTriangle class="h-7 w-7" strokeWidth={2} />
			Confirmar Exclusão
		</h3>

		<div class="alert alert-warning mb-4">
			<AlertTriangle class="h-6 w-6 shrink-0 stroke-current" strokeWidth={2} />
			<div>
				<span class="font-bold">Atenção!</span>
				<p class="text-sm">Esta ação não pode ser desfeita!</p>
			</div>
		</div>

		{#if toDelete}
			<div class="bg-base-200 mb-4 rounded-lg p-4">
				<p class="text-base-content/70 mb-3 text-sm">
					Você está prestes a excluir o seguinte funcionário:
				</p>
				<div class="space-y-2">
					<div class="flex items-center gap-2">
						<User class="text-primary h-5 w-5" strokeWidth={2} />
						<strong class="text-error text-lg">{toDelete.nome}</strong>
					</div>
					<div class="flex items-center gap-2 text-sm">
						<span class="text-base-content/60">CPF:</span>
						<span class="font-semibold">{toDelete.cpf}</span>
					</div>
					<div class="flex items-center gap-2 text-sm">
						<span class="text-base-content/60">Matrícula:</span>
						<span class="badge badge-ghost">{toDelete.matricula}</span>
					</div>
				</div>
			</div>

			<p class="text-base-content/70 mb-6 text-center text-sm">Tem certeza que deseja continuar?</p>
		{/if}

		<div class="modal-action justify-between">
			<button class="btn gap-2" onclick={closeDeleteModal} disabled={deletingId !== null}>
				<X class="h-5 w-5" strokeWidth={2} />
				Cancelar
			</button>
			<button class="btn btn-error gap-2" onclick={confirmDelete} disabled={deletingId !== null}>
				{#if deletingId}
					<span class="loading loading-spinner loading-sm"></span>
					Excluindo...
				{:else}
					<Trash2 class="h-5 w-5" strokeWidth={2} />
					Confirmar Exclusão
				{/if}
			</button>
		</div>
	</div>
	<form method="dialog" class="modal-backdrop">
		<button>close</button>
	</form>
</dialog>
