<script lang="ts">
  import { useConvexClient } from "convex-svelte";
  import { api } from "@sgse-app/backend/convex/_generated/api";
  import { goto } from "$app/navigation";
  import { onMount } from "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("/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="text-sm breadcrumbs mb-4">
  <ul>
    <li>
      <a href="/" class="text-primary hover:text-primary-focus">
        <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6" />
        </svg>
        Dashboard
      </a>
    </li>
    <li>
      <a href="/recursos-humanos" class="text-primary hover:text-primary-focus">Recursos Humanos</a>
    </li>
    <li>
      <a href="/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="flex items-center gap-3 mb-2">
    <div class="p-3 bg-error/10 rounded-xl">
      <svg xmlns="http://www.w3.org/2000/svg" class="h-8 w-8 text-error" fill="none" viewBox="0 0 24 24" stroke="currentColor">
        <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>
    </div>
    <div class="flex-1">
      <h1 class="text-3xl font-bold text-base-content">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 btn-ghost gap-2"
      onclick={back}
    >
      <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="M10 19l-7-7m0 0l7-7m-7 7h18" />
      </svg>
      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"}
      <svg xmlns="http://www.w3.org/2000/svg" class="stroke-current shrink-0 h-6 w-6" fill="none" viewBox="0 0 24 24">
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
      </svg>
    {:else}
      <svg xmlns="http://www.w3.org/2000/svg" class="stroke-current shrink-0 h-6 w-6" 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>
    {/if}
    <span class="font-semibold">{notice.text}</span>
    <button class="btn btn-sm btn-ghost" onclick={() => notice = null} aria-label="Fechar alerta">
      <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" 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>
{/if}

<!-- Card de Filtros -->
<div class="card bg-base-100 shadow-xl mb-6">
  <div class="card-body">
    <div class="flex items-center justify-between mb-4">
      <h2 class="card-title text-lg">
        <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 text-primary" fill="none" viewBox="0 0 24 24" stroke="currentColor">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 4a1 1 0 011-1h16a1 1 0 011 1v2.586a1 1 0 01-.293.707l-6.414 6.414a1 1 0 00-.293.707V17l-4 4v-6.586a1 1 0 00-.293-.707L3.293 7.293A1 1 0 013 6.586V4z" />
        </svg>
        Filtros de Busca
      </h2>
      {#if filtro}
        <button class="btn btn-sm btn-ghost gap-2" onclick={limparFiltro}>
          <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" 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>
          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 w-full focus:input-primary" 
        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 text-lg mb-4">
      <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 text-primary" fill="none" viewBox="0 0 24 24" stroke="currentColor">
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4.354a4 4 0 110 5.292M15 21H3v-1a6 6 0 0112 0v1zm0 0h6v-1a6 6 0 00-9-5.197M13 7a4 4 0 11-8 0 4 4 0 018 0z" />
      </svg>
      Lista de Funcionários
    </h2>

    {#if list.length === 0}
      <div class="flex flex-col items-center justify-center py-12 text-center">
        <div class="p-4 bg-base-200 rounded-full mb-4">
          <svg xmlns="http://www.w3.org/2000/svg" class="h-12 w-12 text-base-content/30" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20 13V6a2 2 0 00-2-2H6a2 2 0 00-2 2v7m16 0v5a2 2 0 01-2 2H6a2 2 0 01-2-2v-5m16 0h-2.586a1 1 0 00-.707.293l-2.414 2.414a1 1 0 01-.707.293h-3.172a1 1 0 01-.707-.293l-2.414-2.414A1 1 0 006.586 13H4" />
          </svg>
        </div>
        <p class="text-lg font-semibold text-base-content/70">Nenhum funcionário cadastrado</p>
        <p class="text-sm text-base-content/50 mt-2">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="p-4 bg-base-200 rounded-full mb-4">
          <svg xmlns="http://www.w3.org/2000/svg" class="h-12 w-12 text-base-content/30" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
          </svg>
        </div>
        <p class="text-lg font-semibold text-base-content/70">Nenhum resultado encontrado</p>
        <p class="text-sm text-base-content/50 mt-2">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 table-zebra">
          <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-base text-center">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)}
                  >
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                      <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>
                    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="font-bold text-2xl mb-4 flex items-center gap-2 text-error">
      <svg xmlns="http://www.w3.org/2000/svg" class="h-7 w-7" fill="none" viewBox="0 0 24 24" stroke="currentColor">
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
      </svg>
      Confirmar Exclusão
    </h3>
    
    <div class="alert alert-warning mb-4">
      <svg xmlns="http://www.w3.org/2000/svg" class="stroke-current shrink-0 h-6 w-6" fill="none" viewBox="0 0 24 24">
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"/>
      </svg>
      <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 rounded-lg p-4 mb-4">
        <p class="text-sm text-base-content/70 mb-3">Você está prestes a excluir o seguinte funcionário:</p>
        <div class="space-y-2">
          <div class="flex items-center gap-2">
            <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 text-primary" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
            </svg>
            <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-center text-sm text-base-content/70 mb-6">
        Tem certeza que deseja continuar?
      </p>
    {/if}
    
    <div class="modal-action justify-between">
      <button 
        class="btn btn-ghost gap-2" 
        onclick={closeDeleteModal} 
        disabled={deletingId !== null}
      >
        <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="M6 18L18 6M6 6l12 12" />
        </svg>
        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}
          <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="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>
          Confirmar Exclusão
        {/if}
      </button>
    </div>
  </div>
  <form method="dialog" class="modal-backdrop">
    <button>close</button>
  </form>
</dialog>


