<script lang="ts">
	import { useQuery, useConvexClient } from 'convex-svelte';
	import { api } from '@sgse-app/backend/convex/_generated/api';
	import type { Id, Doc } from '@sgse-app/backend/convex/_generated/dataModel';
	import { Plus, Pencil, Trash2, X } from 'lucide-svelte';

	const client = useConvexClient();

	// Reactive query
	const acoesQuery = useQuery(api.acoes.list, {});
	const acoes = $derived(acoesQuery.data || []);
	const loading = $derived(acoesQuery.isLoading);
	const error = $derived(acoesQuery.error?.message || null);

	// Modal state
	let showModal = $state(false);
	let editingId: string | null = $state(null);
	let formData = $state({
		nome: '',
		tipo: 'projeto' as 'projeto' | 'lei'
	});
	let saving = $state(false);

	function openModal(acao?: Doc<'acoes'>) {
		if (acao) {
			editingId = acao._id;
			formData = {
				nome: acao.nome,
				tipo: acao.tipo
			};
		} else {
			editingId = null;
			formData = {
				nome: '',
				tipo: 'projeto'
			};
		}
		showModal = true;
	}

	function closeModal() {
		showModal = false;
		editingId = null;
	}

	async function handleSubmit(e: Event) {
		e.preventDefault();
		saving = true;
		try {
			if (editingId) {
				await client.mutation(api.acoes.update, {
					id: editingId as Id<'acoes'>,
					...formData
				});
			} else {
				await client.mutation(api.acoes.create, formData);
			}
			closeModal();
		} catch (e) {
			alert('Erro ao salvar: ' + (e as Error).message);
		} finally {
			saving = false;
		}
	}

	async function handleDelete(id: Id<'acoes'>) {
		if (!confirm('Tem certeza que deseja excluir esta ação?')) return;
		try {
			await client.mutation(api.acoes.remove, { id });
		} catch (e) {
			alert('Erro ao excluir: ' + (e as Error).message);
		}
	}
</script>

<div class="container mx-auto p-6">
	<div class="mb-6 flex items-center justify-between">
		<h1 class="text-2xl font-bold">Ações</h1>
		<button
			onclick={() => openModal()}
			class="flex items-center gap-2 rounded-md bg-blue-600 px-4 py-2 text-white hover:bg-blue-700"
		>
			<Plus size={20} />
			Nova Ação
		</button>
	</div>

	{#if loading}
		<p>Carregando...</p>
	{:else if error}
		<p class="text-red-600">{error}</p>
	{:else}
		<div class="overflow-hidden rounded-lg bg-white shadow-md">
			<table class="min-w-full divide-y divide-gray-200">
				<thead class="bg-gray-50">
					<tr>
						<th
							class="px-6 py-3 text-left text-xs font-medium tracking-wider text-gray-500 uppercase"
							>Nome</th
						>
						<th
							class="px-6 py-3 text-left text-xs font-medium tracking-wider text-gray-500 uppercase"
							>Tipo</th
						>
						<th
							class="px-6 py-3 text-right text-xs font-medium tracking-wider text-gray-500 uppercase"
							>Ações</th
						>
					</tr>
				</thead>
				<tbody class="divide-y divide-gray-200 bg-white">
					{#each acoes as acao (acao._id)}
						<tr>
							<td class="px-6 py-4 whitespace-nowrap">{acao.nome}</td>
							<td class="px-6 py-4 whitespace-nowrap">
								<span
									class="inline-flex rounded-full px-2 text-xs leading-5 font-semibold
                  {acao.tipo === 'projeto'
										? 'bg-purple-100 text-purple-800'
										: 'bg-orange-100 text-orange-800'}"
								>
									{acao.tipo === 'projeto' ? 'Projeto' : 'Lei'}
								</span>
							</td>
							<td class="px-6 py-4 text-right text-sm font-medium whitespace-nowrap">
								<button
									onclick={() => openModal(acao)}
									class="mr-4 text-indigo-600 hover:text-indigo-900"
								>
									<Pencil size={18} />
								</button>
								<button
									onclick={() => handleDelete(acao._id)}
									class="text-red-600 hover:text-red-900"
								>
									<Trash2 size={18} />
								</button>
							</td>
						</tr>
					{/each}
					{#if acoes.length === 0}
						<tr>
							<td colspan="3" class="px-6 py-4 text-center text-gray-500"
								>Nenhuma ação cadastrada.</td
							>
						</tr>
					{/if}
				</tbody>
			</table>
		</div>
	{/if}

	{#if showModal}
		<div
			class="bg-opacity-50 fixed inset-0 z-50 flex h-full w-full items-center justify-center overflow-y-auto bg-gray-600"
		>
			<div class="relative w-full max-w-md rounded-lg bg-white p-8 shadow-xl">
				<button
					onclick={closeModal}
					class="absolute top-4 right-4 text-gray-400 hover:text-gray-600"
				>
					<X size={24} />
				</button>
				<h2 class="mb-6 text-xl font-bold">{editingId ? 'Editar' : 'Novo'} Ação</h2>

				<form onsubmit={handleSubmit}>
					<div class="mb-4">
						<label class="mb-2 block text-sm font-bold text-gray-700" for="nome"> Nome </label>
						<input
							class="focus:shadow-outline w-full appearance-none rounded border px-3 py-2 leading-tight text-gray-700 shadow focus:outline-none"
							id="nome"
							type="text"
							bind:value={formData.nome}
							required
						/>
					</div>

					<div class="mb-6">
						<label class="mb-2 block text-sm font-bold text-gray-700" for="tipo"> Tipo </label>
						<select
							class="focus:shadow-outline w-full rounded border px-3 py-2 leading-tight text-gray-700 shadow focus:outline-none"
							id="tipo"
							bind:value={formData.tipo}
						>
							<option value="projeto">Projeto</option>
							<option value="lei">Lei</option>
						</select>
					</div>

					<div class="flex items-center justify-end">
						<button
							type="button"
							onclick={closeModal}
							class="mr-2 rounded bg-gray-300 px-4 py-2 font-bold text-gray-800 hover:bg-gray-400"
						>
							Cancelar
						</button>
						<button
							type="submit"
							disabled={saving}
							class="focus:shadow-outline rounded bg-blue-600 px-4 py-2 font-bold text-white hover:bg-blue-700 focus:outline-none disabled:opacity-50"
						>
							{saving ? 'Salvando...' : 'Salvar'}
						</button>
					</div>
				</form>
			</div>
		</div>
	{/if}
</div>
