<script lang="ts">
  import { useQuery, useConvexClient } from "convex-svelte";
  import { api } from "@sgse-app/backend/convex/_generated/api";
  import { notificacoesCount } from "$lib/stores/chatStore";
  import { formatDistanceToNow } from "date-fns";
  import { ptBR } from "date-fns/locale";
  import { onMount } from "svelte";
  import { authStore } from "$lib/stores/auth.svelte";

  // Queries e Client
  const client = useConvexClient();
  const notificacoesQuery = useQuery(api.chat.obterNotificacoes, {
    apenasPendentes: true,
  });
  const countQuery = useQuery(api.chat.contarNotificacoesNaoLidas, {});

  let dropdownOpen = $state(false);
  let notificacoesFerias = $state<any[]>([]);

  // Helpers para obter valores das queries
  const count = $derived(
    (typeof countQuery === "number" ? countQuery : countQuery?.data) ?? 0
  );
  const notificacoes = $derived(
    (Array.isArray(notificacoesQuery)
      ? notificacoesQuery
      : notificacoesQuery?.data) ?? []
  );

  // Atualizar contador no store
  $effect(() => {
    const totalNotificacoes = count + (notificacoesFerias?.length || 0);
    notificacoesCount.set(totalNotificacoes);
  });

  // Buscar notificações de férias
  async function buscarNotificacoesFerias() {
    try {
      const usuarioStore = authStore;

      if (usuarioStore.usuario?._id) {
        const notifsFerias = await client.query(
          api.ferias.obterNotificacoesNaoLidas,
          {
            usuarioId: usuarioStore.usuario._id as any,
          }
        );
        notificacoesFerias = notifsFerias || [];
      }
    } catch (e) {
      console.error("Erro ao buscar notificações de férias:", e);
    }
  }

  // Atualizar notificações de férias periodicamente
  $effect(() => {
    buscarNotificacoesFerias();
    const interval = setInterval(buscarNotificacoesFerias, 30000); // A cada 30s
    return () => clearInterval(interval);
  });

  function formatarTempo(timestamp: number): string {
    try {
      return formatDistanceToNow(new Date(timestamp), {
        addSuffix: true,
        locale: ptBR,
      });
    } catch {
      return "agora";
    }
  }

  async function handleMarcarTodasLidas() {
    await client.mutation(api.chat.marcarTodasNotificacoesLidas, {});
    // Marcar todas as notificações de férias como lidas
    for (const notif of notificacoesFerias) {
      await client.mutation(api.ferias.marcarComoLida, {
        notificacaoId: notif._id,
      });
    }
    dropdownOpen = false;
    await buscarNotificacoesFerias();
  }

  async function handleClickNotificacao(notificacaoId: string) {
    await client.mutation(api.chat.marcarNotificacaoLida, {
      notificacaoId: notificacaoId as any,
    });
    dropdownOpen = false;
  }

  async function handleClickNotificacaoFerias(notificacaoId: string) {
    await client.mutation(api.ferias.marcarComoLida, {
      notificacaoId: notificacaoId as any,
    });
    await buscarNotificacoesFerias();
    dropdownOpen = false;
    // Redirecionar para a página de férias
    window.location.href = "/recursos-humanos/ferias";
  }

  function toggleDropdown() {
    dropdownOpen = !dropdownOpen;
  }

  // Fechar dropdown ao clicar fora
  onMount(() => {
    function handleClickOutside(event: MouseEvent) {
      const target = event.target as HTMLElement;
      if (!target.closest(".notification-bell")) {
        dropdownOpen = false;
      }
    }

    document.addEventListener("click", handleClickOutside);
    return () => document.removeEventListener("click", handleClickOutside);
  });
</script>

<div class="dropdown dropdown-end notification-bell">
  <!-- Botão de Notificação ULTRA MODERNO (igual ao perfil) -->
  <button
    type="button"
    tabindex="0"
    class="relative flex items-center justify-center w-14 h-14 rounded-2xl overflow-hidden group transition-all duration-300 hover:scale-105"
    style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); box-shadow: 0 8px 24px -4px rgba(102, 126, 234, 0.4);"
    onclick={toggleDropdown}
    aria-label="Notificações"
  >
    <!-- Efeito de brilho no hover -->
    <div
      class="absolute inset-0 bg-gradient-to-br from-white/0 to-white/20 opacity-0 group-hover:opacity-100 transition-opacity duration-300"
    ></div>

    <!-- Anel de pulso sutil -->
    <div
      class="absolute inset-0 rounded-2xl"
      style="animation: pulse-ring-subtle 3s cubic-bezier(0.4, 0, 0.6, 1) infinite;"
    ></div>

    <!-- Glow effect quando tem notificações -->
    {#if count && count > 0}
      <div
        class="absolute inset-0 rounded-2xl bg-error/30 blur-lg animate-pulse"
      ></div>
    {/if}

    <!-- Ícone do sino PREENCHIDO moderno -->
    <svg
      xmlns="http://www.w3.org/2000/svg"
      viewBox="0 0 24 24"
      fill="currentColor"
      class="w-7 h-7 text-white relative z-10 transition-all duration-300 group-hover:scale-110"
      style="filter: drop-shadow(0 2px 8px rgba(0,0,0,0.3)); animation: {count &&
      count > 0
        ? 'bell-ring 2s ease-in-out infinite'
        : 'none'};"
    >
      <path
        fill-rule="evenodd"
        d="M5.25 9a6.75 6.75 0 0113.5 0v.75c0 2.123.8 4.057 2.118 5.52a.75.75 0 01-.297 1.206c-1.544.57-3.16.99-4.831 1.243a3.75 3.75 0 11-7.48 0 24.585 24.585 0 01-4.831-1.244.75.75 0 01-.298-1.205A8.217 8.217 0 005.25 9.75V9zm4.502 8.9a2.25 2.25 0 104.496 0 25.057 25.057 0 01-4.496 0z"
        clip-rule="evenodd"
      />
    </svg>

    <!-- Badge premium MODERNO com gradiente -->
    {#if count + (notificacoesFerias?.length || 0) > 0}
      {@const totalCount = count + (notificacoesFerias?.length || 0)}
      <span
        class="absolute -top-1 -right-1 flex h-6 w-6 items-center justify-center rounded-full text-white text-[10px] font-black shadow-xl ring-2 ring-white z-20"
        style="background: linear-gradient(135deg, #ff416c, #ff4b2b); box-shadow: 0 8px 24px -4px rgba(255, 65, 108, 0.6), 0 4px 12px -2px rgba(255, 75, 43, 0.4); animation: badge-bounce 2s ease-in-out infinite;"
      >
        {totalCount > 9 ? "9+" : totalCount}
      </span>
    {/if}
  </button>

  {#if dropdownOpen}
    <!-- svelte-ignore a11y_no_noninteractive_tabindex -->
    <div
      tabindex="0"
      class="dropdown-content z-50 mt-3 w-80 max-h-96 overflow-auto rounded-box bg-base-100 p-2 shadow-2xl border border-base-300"
    >
      <!-- Header -->
      <div
        class="flex items-center justify-between px-4 py-2 border-b border-base-300"
      >
        <h3 class="text-lg font-semibold">Notificações</h3>
        {#if count > 0}
          <button
            type="button"
            class="btn btn-ghost btn-xs"
            onclick={handleMarcarTodasLidas}
          >
            Marcar todas como lidas
          </button>
        {/if}
      </div>

      <!-- Lista de notificações -->
      <div class="py-2">
        {#if notificacoes.length > 0}
          {#each notificacoes.slice(0, 10) as notificacao (notificacao._id)}
            <button
              type="button"
              class="w-full text-left px-4 py-3 hover:bg-base-200 rounded-lg transition-colors"
              onclick={() => handleClickNotificacao(notificacao._id)}
            >
              <div class="flex items-start gap-3">
                <!-- Ícone -->
                <div class="flex-shrink-0 mt-1">
                  {#if notificacao.tipo === "nova_mensagem"}
                    <svg
                      xmlns="http://www.w3.org/2000/svg"
                      fill="none"
                      viewBox="0 0 24 24"
                      stroke-width="1.5"
                      stroke="currentColor"
                      class="w-5 h-5 text-primary"
                    >
                      <path
                        stroke-linecap="round"
                        stroke-linejoin="round"
                        d="M21.75 6.75v10.5a2.25 2.25 0 0 1-2.25 2.25h-15a2.25 2.25 0 0 1-2.25-2.25V6.75m19.5 0A2.25 2.25 0 0 0 19.5 4.5h-15a2.25 2.25 0 0 0-2.25 2.25m19.5 0v.243a2.25 2.25 0 0 1-1.07 1.916l-7.5 4.615a2.25 2.25 0 0 1-2.36 0L3.32 8.91a2.25 2.25 0 0 1-1.07-1.916V6.75"
                      />
                    </svg>
                  {:else if notificacao.tipo === "mencao"}
                    <svg
                      xmlns="http://www.w3.org/2000/svg"
                      fill="none"
                      viewBox="0 0 24 24"
                      stroke-width="1.5"
                      stroke="currentColor"
                      class="w-5 h-5 text-warning"
                    >
                      <path
                        stroke-linecap="round"
                        stroke-linejoin="round"
                        d="M16.5 12a4.5 4.5 0 1 1-9 0 4.5 4.5 0 0 1 9 0Zm0 0c0 1.657 1.007 3 2.25 3S21 13.657 21 12a9 9 0 1 0-2.636 6.364M16.5 12V8.25"
                      />
                    </svg>
                  {:else}
                    <svg
                      xmlns="http://www.w3.org/2000/svg"
                      fill="none"
                      viewBox="0 0 24 24"
                      stroke-width="1.5"
                      stroke="currentColor"
                      class="w-5 h-5 text-info"
                    >
                      <path
                        stroke-linecap="round"
                        stroke-linejoin="round"
                        d="M18 18.72a9.094 9.094 0 0 0 3.741-.479 3 3 0 0 0-4.682-2.72m.94 3.198.001.031c0 .225-.012.447-.037.666A11.944 11.944 0 0 1 12 21c-2.17 0-4.207-.576-5.963-1.584A6.062 6.062 0 0 1 6 18.719m12 0a5.971 5.971 0 0 0-.941-3.197m0 0A5.995 5.995 0 0 0 12 12.75a5.995 5.995 0 0 0-5.058 2.772m0 0a3 3 0 0 0-4.681 2.72 8.986 8.986 0 0 0 3.74.477m.94-3.197a5.971 5.971 0 0 0-.94 3.197M15 6.75a3 3 0 1 1-6 0 3 3 0 0 1 6 0Zm6 3a2.25 2.25 0 1 1-4.5 0 2.25 2.25 0 0 1 4.5 0Zm-13.5 0a2.25 2.25 0 1 1-4.5 0 2.25 2.25 0 0 1 4.5 0Z"
                      />
                    </svg>
                  {/if}
                </div>

                <!-- Conteúdo -->
                <div class="flex-1 min-w-0">
                  <p class="text-sm font-medium text-base-content">
                    {notificacao.titulo}
                  </p>
                  <p class="text-xs text-base-content/70 truncate">
                    {notificacao.descricao}
                  </p>
                  <p class="text-xs text-base-content/50 mt-1">
                    {formatarTempo(notificacao.criadaEm)}
                  </p>
                </div>

                <!-- Indicador de não lida -->
                {#if !notificacao.lida}
                  <div class="flex-shrink-0">
                    <div class="w-2 h-2 rounded-full bg-primary"></div>
                  </div>
                {/if}
              </div>
            </button>
          {/each}
        {/if}

        <!-- Notificações de Férias -->
        {#if notificacoesFerias.length > 0}
          {#if notificacoes.length > 0}
            <div class="divider my-2 text-xs">Férias</div>
          {/if}
          {#each notificacoesFerias.slice(0, 5) as notificacao (notificacao._id)}
            <button
              type="button"
              class="w-full text-left px-4 py-3 hover:bg-base-200 rounded-lg transition-colors"
              onclick={() => handleClickNotificacaoFerias(notificacao._id)}
            >
              <div class="flex items-start gap-3">
                <!-- Ícone -->
                <div class="flex-shrink-0 mt-1">
                  <svg
                    xmlns="http://www.w3.org/2000/svg"
                    class="w-5 h-5 text-purple-600"
                    fill="none"
                    viewBox="0 0 24 24"
                    stroke="currentColor"
                  >
                    <path
                      stroke-linecap="round"
                      stroke-linejoin="round"
                      stroke-width="2"
                      d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"
                    />
                  </svg>
                </div>

                <!-- Conteúdo -->
                <div class="flex-1 min-w-0">
                  <p class="text-sm font-medium text-base-content">
                    {notificacao.mensagem}
                  </p>
                  <p class="text-xs text-base-content/50 mt-1">
                    {formatarTempo(notificacao._creationTime)}
                  </p>
                </div>

                <!-- Badge -->
                <div class="flex-shrink-0">
                  <div class="badge badge-primary badge-xs"></div>
                </div>
              </div>
            </button>
          {/each}
        {/if}

        <!-- Sem notificações -->
        {#if notificacoes.length === 0 && notificacoesFerias.length === 0}
          <div class="px-4 py-8 text-center text-base-content/50">
            <svg
              xmlns="http://www.w3.org/2000/svg"
              fill="none"
              viewBox="0 0 24 24"
              stroke-width="1.5"
              stroke="currentColor"
              class="w-12 h-12 mx-auto mb-2 opacity-50"
            >
              <path
                stroke-linecap="round"
                stroke-linejoin="round"
                d="M9.143 17.082a24.248 24.248 0 0 0 3.844.148m-3.844-.148a23.856 23.856 0 0 1-5.455-1.31 8.964 8.964 0 0 0 2.3-5.542m3.155 6.852a3 3 0 0 0 5.667 1.97m1.965-2.277L21 21m-4.225-4.225a23.81 23.81 0 0 0 3.536-1.003A8.967 8.967 0 0 1 18 9.75V9A6 6 0 0 0 6.53 6.53m10.245 10.245L6.53 6.53M3 3l3.53 3.53"
              />
            </svg>
            <p class="text-sm">Nenhuma notificação</p>
          </div>
        {/if}
      </div>
    </div>
  {/if}
</div>

<style>
  @keyframes badge-bounce {
    0%,
    100% {
      transform: scale(1);
    }
    50% {
      transform: scale(1.1);
    }
  }

  @keyframes pulse-ring-subtle {
    0%,
    100% {
      opacity: 0.1;
      transform: scale(1);
    }
    50% {
      opacity: 0.3;
      transform: scale(1.05);
    }
  }

  @keyframes bell-ring {
    0%,
    100% {
      transform: rotate(0deg);
    }
    10%,
    30% {
      transform: rotate(-10deg);
    }
    20%,
    40% {
      transform: rotate(10deg);
    }
    50% {
      transform: rotate(0deg);
    }
  }
</style>
