<script lang="ts">
  import { useQuery } from "convex-svelte";
  import { api } from "@sgse-app/backend/convex/_generated/api";

  let abaAtiva = $state<"atividades" | "logins">("atividades");
  let limite = $state(50);
  
  // Queries com $derived para garantir reatividade
  const atividades = $derived(useQuery(api.logsAtividades.listarAtividades, { limite }));
  const logins = $derived(useQuery(api.logsLogin.listarTodosLogins, { limite }));

  function formatarData(timestamp: number) {
    return new Date(timestamp).toLocaleString('pt-BR', {
      day: '2-digit',
      month: '2-digit',
      year: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    });
  }

  function getAcaoColor(acao: string) {
    const colors: Record<string, string> = {
      criar: "badge-success",
      editar: "badge-warning",
      excluir: "badge-error",
      bloquear: "badge-error",
      desbloquear: "badge-success",
      resetar_senha: "badge-info"
    };
    return colors[acao] || "badge-neutral";
  }
</script>

<div class="container mx-auto px-4 py-6 max-w-7xl">
  <!-- Header -->
  <div class="flex items-center justify-between mb-6">
    <div class="flex items-center gap-4">
      <div class="p-3 bg-accent/10 rounded-xl">
        <svg xmlns="http://www.w3.org/2000/svg" class="h-8 w-8 text-accent" fill="none" viewBox="0 0 24 24" stroke="currentColor">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
        </svg>
      </div>
      <div>
        <h1 class="text-3xl font-bold text-base-content">Auditoria e Logs</h1>
        <p class="text-base-content/60 mt-1">Histórico completo de atividades e acessos</p>
      </div>
    </div>
  </div>

  <!-- Tabs -->
  <div class="tabs tabs-boxed mb-6 bg-base-100 shadow-lg p-2">
    <button 
      class="tab {abaAtiva === 'atividades' ? 'tab-active' : ''}"
      onclick={() => abaAtiva = "atividades"}
    >
      <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mr-2" fill="none" viewBox="0 0 24 24" stroke="currentColor">
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2" />
      </svg>
      Atividades no Sistema
    </button>
    <button 
      class="tab {abaAtiva === 'logins' ? 'tab-active' : ''}"
      onclick={() => abaAtiva = "logins"}
    >
      <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mr-2" fill="none" viewBox="0 0 24 24" stroke="currentColor">
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 16l-4-4m0 0l4-4m-4 4h14m-5 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h7a3 3 0 013 3v1" />
      </svg>
      Histórico de Logins
    </button>
  </div>

  <!-- Controles -->
  <div class="card bg-base-100 shadow-xl mb-6">
    <div class="card-body">
      <div class="flex flex-wrap items-center justify-between gap-4">
        <div class="form-control">
          <label class="label">
            <span class="label-text">Quantidade de registros</span>
          </label>
          <select bind:value={limite} class="select select-bordered">
            <option value={20}>20 registros</option>
            <option value={50}>50 registros</option>
            <option value={100}>100 registros</option>
            <option value={200}>200 registros</option>
          </select>
        </div>
        
        <div class="flex gap-2">
          <button class="btn btn-outline btn-primary">
            <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="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
            </svg>
            Exportar CSV
          </button>
          <button class="btn btn-outline btn-secondary">
            <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 Avançados
          </button>
        </div>
      </div>
    </div>
  </div>

  <!-- Conteúdo -->
  {#if abaAtiva === "atividades"}
    <div class="card bg-base-100 shadow-xl">
      <div class="card-body">
        <h2 class="card-title mb-4">Atividades Recentes</h2>
        
        {#if !atividades?.data}
          <div class="flex justify-center py-10">
            <span class="loading loading-spinner loading-lg text-primary"></span>
          </div>
        {:else if atividades.data.length === 0}
          <div class="text-center py-10 text-base-content/60">
            Nenhuma atividade registrada
          </div>
        {:else}
          <div class="overflow-x-auto">
            <table class="table table-sm">
              <thead>
                <tr>
                  <th>Data/Hora</th>
                  <th>Usuário</th>
                  <th>Ação</th>
                  <th>Recurso</th>
                  <th>Detalhes</th>
                </tr>
              </thead>
              <tbody>
                {#each atividades.data as atividade}
                  <tr class="hover">
                    <td class="font-mono text-xs">{formatarData(atividade.timestamp)}</td>
                    <td>
                      <div class="font-medium">{atividade.usuarioNome || "Sistema"}</div>
                      <div class="text-xs opacity-60">{atividade.usuarioMatricula || "-"}</div>
                    </td>
                    <td>
                      <span class="badge {getAcaoColor(atividade.acao)} badge-sm">
                        {atividade.acao}
                      </span>
                    </td>
                    <td class="font-medium">{atividade.recurso}</td>
                    <td>
                      <div class="text-xs max-w-md truncate" title={atividade.detalhes}>
                        {atividade.detalhes || "-"}
                      </div>
                    </td>
                  </tr>
                {/each}
              </tbody>
            </table>
          </div>
        {/if}
      </div>
    </div>
  {:else}
    <div class="card bg-base-100 shadow-xl">
      <div class="card-body">
        <h2 class="card-title mb-4">Histórico de Logins</h2>
        
        {#if !logins?.data}
          <div class="flex justify-center py-10">
            <span class="loading loading-spinner loading-lg text-primary"></span>
          </div>
        {:else if logins.data.length === 0}
          <div class="text-center py-10 text-base-content/60">
            Nenhum login registrado
          </div>
        {:else}
          <div class="overflow-x-auto">
            <table class="table table-sm">
              <thead>
                <tr>
                  <th>Data/Hora</th>
                  <th>Usuário/Email</th>
                  <th>Status</th>
                  <th>IP</th>
                  <th>Dispositivo</th>
                  <th>Navegador</th>
                  <th>Sistema</th>
                </tr>
              </thead>
              <tbody>
                {#each logins.data as login}
                  <tr class="hover">
                    <td class="font-mono text-xs">{formatarData(login.timestamp)}</td>
                    <td class="text-sm">{login.matriculaOuEmail}</td>
                    <td>
                      {#if login.sucesso}
                        <span class="badge badge-success badge-sm">Sucesso</span>
                      {:else}
                        <span class="badge badge-error badge-sm">Falhou</span>
                        {#if login.motivoFalha}
                          <div class="text-xs text-error mt-1">{login.motivoFalha}</div>
                        {/if}
                      {/if}
                    </td>
                    <td class="font-mono text-xs">{login.ipAddress || "-"}</td>
                    <td class="text-xs">{login.device || "-"}</td>
                    <td class="text-xs">{login.browser || "-"}</td>
                    <td class="text-xs">{login.sistema || "-"}</td>
                  </tr>
                {/each}
              </tbody>
            </table>
          </div>
        {/if}
      </div>
    </div>
  {/if}

  <!-- Informação -->
  <div class="alert alert-info mt-6">
    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" class="stroke-current shrink-0 w-6 h-6">
      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
    </svg>
    <span>Os logs são armazenados permanentemente e não podem ser alterados ou excluídos.</span>
  </div>
</div>

