<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import { useAuthentik } from '@/composables/useAuthentik.js';
import { Badge, Button, DropdownMenu, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuLabel } from '@/components/ui';
import UserAvatar from './UserAvatar.vue';

const {
  user,
  isAuthenticated,
  isLoading,
  fetchUserData,
  logout,
  goToProfile,
  checkSessionStatus,
} = useAuthentik();

const isMenuOpen = ref(false);

const toggleMenu = () => {
  isMenuOpen.value = !isMenuOpen.value;
};

const handleLogout = () => {
  isMenuOpen.value = false;
  logout();
};

const handleGoToProfile = () => {
  isMenuOpen.value = false;
  goToProfile();
};

const handleCheckSession = () => {
  isMenuOpen.value = false;
  checkSessionStatus();
};

const handleClickOutside = (event) => {
  const dropdown = event.target.closest('.user-dropdown-container');
  if (!dropdown) {
    isMenuOpen.value = false;
  }
};

onMounted(() => {
  fetchUserData();
  document.addEventListener('click', handleClickOutside);
});

onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside);
});
</script>

<template>
  <div class="user-dropdown-container relative">
    <!-- Loading state -->
    <Badge v-if="isLoading" variant="secondary">
      <span class="text-muted">Cargando...</span>
    </Badge>

    <!-- Not authenticated -->
    <Badge v-else-if="!isAuthenticated" variant="secondary">
      <span class="text-muted">No autenticado</span>
    </Badge>

    <!-- Authenticated - Show dropdown -->
    <div v-else class="relative">
      <Button variant="ghost" class="gap-2" @click="toggleMenu">
        <UserAvatar :user="user" />
        <span class="text-sm font-medium">{{ user.name || user.username }}</span>
      </Button>

      <div
        v-if="isMenuOpen"
        class="absolute right-0 top-full mt-1.5 min-w-[280px] max-w-[320px] glass-card p-1.5 shadow-lg border border-pink-200 dark:border-pink-600/50 z-50 animate-slide-in"
      >
        <!-- User Info -->
        <div class="flex items-center gap-3 p-3">
          <UserAvatar :user="user" />
          <div class="flex-1 min-w-0">
            <div class="font-semibold text-sm truncate">{{ user.name || user.username }}</div>
            <div class="text-xs text-muted truncate">{{ user.email }}</div>
          </div>
        </div>

        <hr class="border-border my-1" />

        <!-- User Metadata -->
        <div class="p-2 space-y-2">
          <div v-if="user.uid" class="text-xs space-y-1">
            <span class="text-muted">ID:</span>
            <span class="font-mono text-[11px] break-all ml-1">{{ user.uid }}</span>
          </div>
          <div v-if="user.groups && user.groups.length > 0" class="text-xs space-y-1">
            <span class="text-muted">Grupos:</span>
            <div class="flex flex-wrap gap-1 mt-1">
              <Badge
                v-for="group in user.groups"
                :key="group"
                variant="secondary"
                class="text-[11px] py-0.5 px-1.5"
              >
                {{ group }}
              </Badge>
            </div>
          </div>
        </div>

        <hr class="border-border my-1" />

        <!-- Actions -->
        <div class="p-1 space-y-1">
          <Button
            variant="ghost"
            class="w-full justify-start gap-2 text-sm"
            @click="handleGoToProfile"
          >
            <img class="size-4 opacity-90" src="/icons/user-plus.svg" alt="perfil" />
            Ver Perfil en Authentik
          </Button>

          <Button
            variant="ghost"
            class="w-full justify-start gap-2 text-sm"
            @click="handleCheckSession"
          >
            <img class="size-4 opacity-90" src="/icons/settings.svg" alt="info" />
            Verificar Sesión
          </Button>

          <Button
            variant="danger"
            class="w-full justify-start gap-2 text-sm"
            @click="handleLogout"
          >
            <span class="text-base">⎋</span>
            Cerrar Sesión
          </Button>
        </div>
      </div>
    </div>
  </div>
</template>
