<script setup>
import { computed, ref } from "vue";
import { useRouter } from "vue-router";
import { useAuth } from "../composables/useAuth";
import { useExportNotifications } from "../composables/useExportNotifications";
import { useRealtimeNotifications } from "../composables/useRealtimeNotifications";
import { useLayout } from "./composables/layout";
import AppBreadcrumb from "./AppBreadcrumb.vue";
import MaestroLogo from "../components/branding/MaestroLogo.vue";

const router = useRouter();
const { logout, user } = useAuth();

const {
  visibleReadyExports,
  startDownload,
  clearAllReady,
  clearing,
  refreshSoon,
} = useExportNotifications();
const { hasExportNotifications, hasMessageNotifications } =
  useRealtimeNotifications();

const selectedExportTab = ref("downloads");

const profileInitials = computed(() => {
  const n = user.value?.name;
  if (!n || typeof n !== "string") return "?";
  return n
    .split(/\s+/)
    .filter(Boolean)
    .map((s) => s[0])
    .join("")
    .slice(0, 2)
    .toUpperCase();
});

const { layoutState, isDarkTheme, toggleMenu } = useLayout();

async function onLogout(event) {
  event.preventDefault();
  await logout();
  await router.push({ name: "login" });
}

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

function handleClearExportsClick() {
  if (selectedExportTab.value === "downloads") {
    clearAllReady();
    hasExportNotifications.value = false;
    hasMessageNotifications.value = false;
  }
}

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

function toggleSearchBar() {
  layoutState.searchBarActive = !layoutState.searchBarActive;
}
</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>
      <MaestroLogo
        class="horizontal-logo"
        :compact="false"
        foreground="light"
      />
      <span class="topbar-separator" />
      <AppBreadcrumb />
      <MaestroLogo
        class="mobile-logo"
        :compact="false"
        :foreground="isDarkTheme ? 'light' : 'dark'"
      />
    </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="Notifications and exports"
            @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>Notifications</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"
              >
                Clear all
              </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'"
              >
                Messages
              </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 flex-1 min-w-0">
                      <span
                        class="label-small text-left text-surface-950 dark:text-surface-0 truncate"
                      >
                        {{ 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 shrink-0" />
                  </button>
                </li>
              </ul>
              <div
                v-else
                class="px-6 py-4 text-sm text-surface-500 dark:text-surface-400"
              >
                No files ready to download.
              </div>
            </div>

            <div v-else class="px-6 py-4 text-sm text-surface-500 dark:text-surface-400">
              No messages yet.
            </div>
          </div>
        </li>

        <li class="profile-item static sm:relative">
          <a
            class="bg-none! border-none! outline-none!"
            v-styleclass="{
              selector: '@next',
              enterFromClass: 'hidden',
              enterActiveClass: 'p-anchored-overlay-enter-active',
              leaveActiveClass: 'p-anchored-overlay-leave-active',
              leaveToClass: 'hidden',
              hideOnOutsideClick: true,
            }"
          >
            <Avatar :label="profileInitials" pt:image:class="rounded-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>
                <a
                  href="#"
                  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="onLogout"
                >
                  <i class="pi pi-power-off" />
                  <span>Log out</span>
                </a>
              </li>
            </ul>
          </div>
        </li>
      </ul>
    </div>
  </div>
</template>
