<script lang="ts">
  import { useConvexClient } from "convex-svelte";
  import { api } from "@sgse-app/backend/convex/_generated/api";
  import { goto } from "$app/navigation";
  import type { SimboloTipo } from "@sgse-app/backend/convex/schema";
  import PrintModal from "$lib/components/PrintModal.svelte";

  const client = useConvexClient();

  let list: Array<any> = [];
  let filtered: Array<any> = [];
  let selectedId: string | null = null;
  let openMenuId: string | null = null;
  let funcionarioParaImprimir: any = null;

  let filtroNome = "";
  let filtroCPF = "";
  let filtroMatricula = "";
  let filtroTipo: SimboloTipo | "" = "";

  function applyFilters() {
    const nome = filtroNome.toLowerCase();
    const cpf = filtroCPF.replace(/\D/g, "");
    const mat = filtroMatricula.toLowerCase();
    filtered = list.filter((f) => {
      const okNome = !nome || (f.nome || "").toLowerCase().includes(nome);
      const okCPF = !cpf || (f.cpf || "").includes(cpf);
      const okMat = !mat || (f.matricula || "").toLowerCase().includes(mat);
      const okTipo = !filtroTipo || f.simboloTipo === filtroTipo;
      return okNome && okCPF && okMat && okTipo;
    });
  }

  async function load() {
    list = await client.query(api.funcionarios.getAll, {} as any);
    applyFilters();
  }

  function editSelected() {
    if (selectedId) goto(`/recursos-humanos/funcionarios/${selectedId}/editar`);
  }

  async function openPrintModal(funcionarioId: string) {
    try {
      const data = await client.query(api.funcionarios.getFichaCompleta, { 
        id: funcionarioId as any 
      });
      funcionarioParaImprimir = data;
    } catch (err) {
      console.error("Erro ao carregar funcionário:", err);
      alert("Erro ao carregar dados para impressão");
    }
  }

  function navCadastro() { goto("/recursos-humanos/funcionarios/cadastro"); }

  load();

  function toggleMenu(id: string) {
    openMenuId = openMenuId === id ? null : id;
  }
  $: needsScroll = filtered.length > 8;
</script>

<main class="container mx-auto px-4 py-4">
  <!-- Breadcrumb -->
  <div class="text-sm breadcrumbs mb-4">
    <ul>
      <li><a href="/recursos-humanos" class="text-primary hover:underline">Recursos Humanos</a></li>
      <li>Funcionários</li>
    </ul>
  </div>

  <!-- Cabeçalho -->
  <div class="mb-6">
    <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
      <div class="flex items-center gap-4">
        <div class="p-3 bg-blue-500/20 rounded-xl">
          <svg xmlns="http://www.w3.org/2000/svg" class="h-8 w-8 text-blue-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z" />
          </svg>
        </div>
        <div>
          <h1 class="text-3xl font-bold text-primary">Funcionários Cadastrados</h1>
          <p class="text-base-content/70">Gerencie os funcionários da secretaria</p>
        </div>
      </div>
      <button class="btn btn-primary btn-lg gap-2" onclick={navCadastro}>
        <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
          <path fill-rule="evenodd" d="M10 3a1 1 0 011 1v5h5a1 1 0 110 2h-5v5a1 1 0 11-2 0v-5H4a1 1 0 110-2h5V4a1 1 0 011-1z" clip-rule="evenodd" />
        </svg>
        Novo Funcionário
      </button>
    </div>
  </div>

  <!-- Filtros -->
  <div class="card bg-base-100 shadow-xl mb-6">
    <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" 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 Pesquisa
      </h2>
      <div class="grid grid-cols-1 md:grid-cols-4 gap-4 items-end">
        <div class="form-control w-full">
          <label class="label" for="func_nome">
            <span class="label-text font-semibold">Nome</span>
          </label>
          <input 
            id="func_nome" 
            class="input input-bordered focus:input-primary w-full" 
            placeholder="Buscar por nome..."
            bind:value={filtroNome} 
            oninput={applyFilters} 
          />
        </div>
        <div class="form-control w-full">
          <label class="label" for="func_cpf">
            <span class="label-text font-semibold">CPF</span>
          </label>
          <input 
            id="func_cpf" 
            class="input input-bordered focus:input-primary w-full" 
            placeholder="000.000.000-00"
            bind:value={filtroCPF} 
            oninput={applyFilters} 
          />
        </div>
        <div class="form-control w-full">
          <label class="label" for="func_matricula">
            <span class="label-text font-semibold">Matrícula</span>
          </label>
          <input 
            id="func_matricula" 
            class="input input-bordered focus:input-primary w-full" 
            placeholder="Buscar por matrícula..."
            bind:value={filtroMatricula} 
            oninput={applyFilters} 
          />
        </div>
        <div class="form-control w-full">
          <label class="label" for="func_tipo">
            <span class="label-text font-semibold">Símbolo Tipo</span>
          </label>
          <select id="func_tipo" class="select select-bordered focus:select-primary w-full" bind:value={filtroTipo} oninput={applyFilters}>
            <option value="">Todos os tipos</option>
            <option value="cargo_comissionado">Cargo Comissionado</option>
            <option value="funcao_gratificada">Função Gratificada</option>
          </select>
        </div>
      </div>
      {#if filtroNome || filtroCPF || filtroMatricula || filtroTipo}
        <div class="mt-4">
          <button 
            class="btn btn-ghost btn-sm gap-2"
            onclick={() => {
              filtroNome = "";
              filtroCPF = "";
              filtroMatricula = "";
              filtroTipo = "";
              applyFilters();
            }}
          >
            <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>
        </div>
      {/if}
    </div>
  </div>

  <!-- Tabela de Funcionários -->
  <div class="card bg-base-100 shadow-xl">
    <div class="card-body p-0">
      <div class="overflow-x-auto">
        <div class="overflow-y-auto" style="max-height: {filtered.length > 8 ? '600px' : 'none'};">
          <table class="table table-zebra w-full">
            <thead class="sticky top-0 bg-base-200 z-10">
              <tr>
                <th class="font-bold">Nome</th>
                <th class="font-bold">CPF</th>
                <th class="font-bold">Matrícula</th>
                <th class="font-bold">Tipo</th>
                <th class="font-bold">Cidade</th>
                <th class="font-bold">UF</th>
                <th class="text-right font-bold">Ações</th>
              </tr>
            </thead>
            <tbody>
        {#each filtered as f}
          <tr class="hover">
            <td class="font-medium">{f.nome}</td>
            <td>{f.cpf}</td>
            <td>{f.matricula}</td>
            <td>{f.simboloTipo}</td>
            <td>{f.cidade}</td>
            <td>{f.uf}</td>
            <td class="text-right">
              <div class="dropdown dropdown-end" class:dropdown-open={openMenuId === f._id}>
                <button type="button" aria-label="Abrir menu" class="btn btn-ghost btn-sm" onclick={() => toggleMenu(f._id)}>
                  <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor"><path d="M10 6a2 2 0 110-4 2 2 0 010 4zM10 12a2 2 0 110-4 2 2 0 010 4zM10 18a2 2 0 110-4 2 2 0 010 4z"/></svg>
                </button>
                <ul class="dropdown-content menu bg-base-100 rounded-box z-10 w-52 p-2 shadow-lg border border-base-300">
                  <li><a href={`/recursos-humanos/funcionarios/${f._id}`}>Ver Detalhes</a></li>
                  <li><a href={`/recursos-humanos/funcionarios/${f._id}/editar`}>Editar</a></li>
                  <li><a href={`/recursos-humanos/funcionarios/${f._id}/documentos`}>Ver Documentos</a></li>
                  <li><button onclick={() => openPrintModal(f._id)}>Imprimir Ficha</button></li>
                </ul>
              </div>
            </td>
          </tr>
        {/each}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>

  <!-- Informação sobre resultados -->
  <div class="mt-4 text-sm text-base-content/70 text-center">
    Exibindo {filtered.length} de {list.length} funcionário(s)
  </div>

  <!-- Modal de Impressão -->
  {#if funcionarioParaImprimir}
    <PrintModal 
      funcionario={funcionarioParaImprimir} 
      onClose={() => funcionarioParaImprimir = null} 
    />
  {/if}
</main>
