<script setup>
import { computed, ref } from "vue";
import { useLayout } from "../composables/layout/layout.js";
import { useAuth } from "../composables/useAuth.js";
import { useExportNotifications } from "../composables/useExportNotifications.js";
import { useRealtimeNotifications } from "../composables/useRealtimeNotifications.js";
import { useRouter } from "vue-router";
import AppBreadcrumb from "./AppBreadcrumb.vue";
import BaseUserIcon from "../components/base/BaseUserIcon.vue";
import logoWhite from "../assets/layout/images/logo-white.svg";

const { layoutState, toggleMenu } = useLayout();
const router = useRouter();
const { user, logout } = useAuth();
const {
  visibleReadyExports,
  startDownload,
  clearAllReady,
  clearing,
  refreshSoon,
} = useExportNotifications();
const { hasExportNotifications } = useRealtimeNotifications();
const loggingOut = ref(false);
const selectedExportTab = ref("downloads"); // 'downloads' | 'other'

async function handleClearExportsClick() {
  // Currently only downloadable exports are implemented; when "Andere bestanden" gets real data,
  // this function can be extended to clear per type. For now, only clear downloads when that tab is active.
  if (selectedExportTab.value === "downloads") {
    clearAllReady();
  }
}

async function handleBellClick() {
  try {
    await refreshSoon();
  } finally {
    hasExportNotifications.value = false;
  }
}

const profileName = computed(() => {
  const u = user.value;
  if (!u) return "";

  if (u.name) return String(u.name);

  const parts = [u.first_name, u.last_name].filter(Boolean);
  if (parts.length) return parts.join(" ");

  if (u.email) return String(u.email);

  return "";
});

function formatExportDate(isoString) {
  if (!isoString) return "";
  try {
    const date = new Date(isoString);
    return date.toLocaleString();
  } catch {
    return "";
  }
}

function toggleSearchBar() {
  layoutState.searchBarActive = !layoutState.searchBarActive;
}

async function handleLogout() {
  if (loggingOut.value) return;
  loggingOut.value = true;
  try {
    await logout();
  } catch (e) {
    // ignore logout errors for now
  } finally {
    loggingOut.value = false;
    router.replace("/login");
  }
}
</script>

<template>
  <div class="layout-topbar">
    <div class="topbar-left">
      <a tabindex="0" class="menu-button" @click="toggleMenu">
        <i class="pi pi-chevron-left" />
      </a>
      <img
        class="horizontal-logo"
        :src="logoWhite"
        alt="diamond-layout"
      />
      <span class="topbar-separator" />
      <AppBreadcrumb />
      <img
        class="mobile-logo"
        :src="logoWhite"
        alt="diamond-layout"
      />
    </div>

    <div class="topbar-right">
      <ul class="topbar-menu">
        <li class="right-sidebar-item">
          <a
            class="right-sidebar-button cursor-pointer"
            @click="toggleSearchBar"
          >
            <i class="pi pi-search" />
          </a>
        </li>
        <li class="right-sidebar-item static sm:relative">
          <a
            v-styleclass="{
              selector: '@next',
              enterFromClass: 'hidden',
              enterActiveClass: 'p-anchored-overlay-enter-active',
              leaveActiveClass: 'p-anchored-overlay-leave-active',
              leaveToClass: 'hidden',
              hideOnOutsideClick: true,
            }"
            class="right-sidebar-button relative z-50 cursor-pointer"
            aria-label="Bestanden klaar om te downloaden"
            @click="handleBellClick"
          >
            <span
              v-if="hasExportNotifications || visibleReadyExports.length > 0"
              class="w-2 h-2 rounded-full bg-primary absolute top-1.5 right-1.5"
            />
            <i class="pi pi-bell" />
          </a>
          <div
            class="list-none m-0 rounded-2xl border border-surface absolute bg-surface-0 dark:bg-surface-900 overflow-hidden hidden origin-top min-w-72 sm:w-[22rem] mt-2 right-0 z-50 top-auto shadow-[0px_56px_16px_0px_rgba(0,0,0,0.00),0px_36px_14px_0px_rgba(0,0,0,0.01),0px_20px_12px_0px_rgba(0,0,0,0.02),0px_9px_9px_0px_rgba(0,0,0,0.03),0px_2px_5px_0px_rgba(0,0,0,0.04)]"
          >
            <div
              class="p-4 flex items-center justify-between border-b border-surface"
            >
              <div
                class="label-small text-surface-950 dark:text-surface-0 text-left font-semibold"
              >
                <span>Meldingen</span>
              </div>
              <button
                type="button"
                class="ml-auto py-1 px-2 text-surface-950 dark:text-surface-0 label-xsmall hover:bg-emphasis border border-surface rounded-lg shadow-[0px_1px_2px_0px_rgba(18,18,23,0.05)] transition-all disabled:opacity-50 disabled:cursor-default"
                :disabled="clearing"
                @click.stop="handleClearExportsClick"
              >
                Alles wissen
              </button>
            </div>
            <div class="flex items-center border-b border-surface">
              <button
                type="button"
                class="px-3.5 py-2 inline-flex items-center border-b label-small"
                :class="
                  selectedExportTab === 'other'
                    ? 'border-surface-950 dark:border-surface-0 text-primary dark:text-primary-300'
                    : 'border-transparent text-surface-500 dark:text-surface-400'
                "
                @click.stop="selectedExportTab = 'other'"
              >
                Berichten
              </button>
              <button
                type="button"
                class="px-3.5 py-2 inline-flex items-center border-b label-small"
                :class="
                  selectedExportTab === 'downloads'
                    ? 'border-surface-950 dark:border-surface-0 text-primary dark:text-primary-300'
                    : 'border-transparent text-surface-500 dark:text-surface-400'
                "
                @click.stop="selectedExportTab = 'downloads'"
              >
                Downloads
              </button>
            </div>
            <div v-if="selectedExportTab === 'downloads'">
              <ul
                v-if="visibleReadyExports.length > 0"
                class="flex flex-col divide-y divide-[var(--surface-border)] max-h-80 overflow-auto"
              >
                <li v-for="item in visibleReadyExports" :key="item.id">
                  <button
                    type="button"
                    class="w-full text-left flex items-center gap-3 px-6 py-3.5 cursor-pointer hover:bg-primary-50 dark:hover:bg-primary-900/30 transition-all"
                    @click="startDownload(item)"
                  >
                    <div class="flex flex-col">
                      <span
                        class="label-small text-left text-surface-950 dark:text-surface-0"
                      >
                        {{ item.resourceLabel || item.resourceKey }}.csv
                      </span>
                      <span
                        class="label-xsmall text-left text-surface-500 dark:text-surface-400"
                      >
                        {{ formatExportDate(item.createdAt) }}
                      </span>
                    </div>
                    <i
                      class="pi pi-download text-surface-500 dark:text-surface-400 ml-auto"
                    />
                  </button>
                </li>
              </ul>
              <div
                v-else
                class="px-6 py-4 text-sm text-surface-500 dark:text-surface-400"
              >
                Geen bestanden om te downloaden.
              </div>
            </div>
            <div
              v-else
              class="px-6 py-4 text-sm text-surface-500 dark:text-surface-400"
            >
              Geen nieuwe berichten.
            </div>
          </div>
        </li>
        <li class="profile-item static sm:relative">
          <a
            v-styleclass="{
              selector: '@next',
              enterFromClass: 'hidden',
              enterActiveClass: 'p-anchored-overlay-enter-active',
              leaveActiveClass: 'p-anchored-overlay-leave-active',
              leaveToClass: 'hidden',
              hideOnOutsideClick: true,
            }"
            class="group bg-transparent! hover:bg-transparent! border-none! outline-none! p-0! inline-flex items-center justify-center cursor-pointer rounded-full border-11 border-transparent transition-colors duration-150 hover:border-primary-400"
          >
            <BaseUserIcon :name="profileName" size="lg" class="w-10! h-10!" />
          </a>
          <div
            class="list-none p-2 m-0 rounded-2xl border border-surface overflow-hidden absolute bg-surface-0 dark:bg-surface-900 hidden origin-top w-52 mt-2 right-0 z-999 top-auto shadow-[0px_56px_16px_0px_rgba(0,0,0,0.00),0px_36px_14px_0px_rgba(0,0,0,0.01),0px_20px_12px_0px_rgba(0,0,0,0.02),0px_9px_9px_0px_rgba(0,0,0,0.03),0px_2px_5px_0px_rgba(0,0,0,0.04)]"
          >
            <ul class="flex flex-col gap-1">
              <li>
                <RouterLink
                  to="/profile"
                  class="label-small dark:text-surface-400 flex gap-2 py-2 px-2.5 rounded-lg items-center hover:bg-emphasis transition-colors duration-150 cursor-pointer"
                >
                  <i class="pi pi-user" />
                  <span>Profiel</span>
                </RouterLink>
              </li>
              <li>
                <a
                  class="label-small dark:text-surface-400 flex gap-2 py-2 px-2.5 rounded-lg items-center hover:bg-emphasis transition-colors duration-150 cursor-pointer"
                  @click.prevent="handleLogout"
                >
                  <i class="pi pi-power-off" />
                  <span>Afmelden</span>
                </a>
              </li>
            </ul>
          </div>
        </li>
      </ul>
    </div>
  </div>
</template>
