<script setup lang="ts">
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { useTheme } from '@/components/theme-provider'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from '@/components/ui/dropdown-menu'
import { Sun, Moon, Menu, X, User, LogOut, Ticket, Wallet, MessageSquare, Activity, ShoppingCart, Store, Calendar, ShoppingBag, ChevronRight } from 'lucide-vue-next'
import LanguageSwitcher from '@/components/LanguageSwitcher.vue'
import LoginDialog from '@/components/auth/LoginDialog.vue'
import ProfileDialog from '@/components/auth/ProfileDialog.vue'
import CurrencyDisplay from '@/components/ui/CurrencyDisplay.vue'
import { LogoutConfirmDialog } from '@/components/ui/LogoutConfirmDialog'
import { auth } from '@/composables/useAuthService'
import { useMarketPreloader } from '@/modules/market/composables/useMarketPreloader'
import { useMarketStore } from '@/modules/market/stores/market'
import { tryInjectService, SERVICE_TOKENS } from '@/core/di-container'
import { useModularNavigation } from '@/composables/useModularNavigation'

// NavigationItem interface removed as it's handled by useModularNavigation

const router = useRouter()
const { t } = useI18n()
const { theme, setTheme } = useTheme()
const isOpen = ref(false)
const showLoginDialog = ref(false)
const showProfileDialog = ref(false)
const showLogoutConfirm = ref(false)
const marketPreloader = useMarketPreloader()
const marketStore = useMarketStore()
const { navigation: modularNavigation, userMenuItems } = useModularNavigation()

const navigation = modularNavigation

// Get PaymentService from DI for centralized wallet balance
const paymentService = tryInjectService(SERVICE_TOKENS.PAYMENT_SERVICE) as any

// Use PaymentService for total wallet balance
const totalBalance = computed(() => {
  return paymentService?.totalBalance || 0
})

// Try to get chat service from DI (may not be available if chat module not loaded)
const chatService = tryInjectService(SERVICE_TOKENS.CHAT_SERVICE) as any

// Compute total unread messages (reactive)
const totalUnreadMessages = computed(() => {
  return chatService?.totalUnreadCount?.value || 0
})

// Compute cart item count
const cartItemCount = computed(() => {
  return marketStore.totalCartItems
})



const toggleMenu = () => {
  isOpen.value = !isOpen.value
}

const toggleTheme = () => {
  setTheme(theme.value === 'dark' ? 'light' : 'dark')
}

const openLoginDialog = () => {
  showLoginDialog.value = true
  isOpen.value = false // Close mobile menu
}

const openProfileDialog = () => {
  showProfileDialog.value = true
  isOpen.value = false // Close mobile menu
}

const handleLogout = async () => {
  try {
    auth.logout()
    isOpen.value = false
    // Redirect to login page
    router.push('/login')
  } catch (error) {
    console.error('Logout failed:', error)
  }
}
</script>

<template>
  <nav class="w-full text-foreground">
    <div class="flex items-center justify-between">
      <!-- Logo and Desktop Navigation -->
      <div class="flex items-center gap-4 lg:gap-8 xl:gap-12">
        <router-link to="/" class="flex items-center gap-2 text-foreground hover:text-foreground/90">
          <img src="@/assets/logo.png" alt="Logo"
            class="h-10 w-10 sm:h-12 sm:w-12 md:h-14 md:w-14 lg:h-16 lg:w-16 xl:h-20 xl:w-20" />
          <span class="font-semibold text-base lg:text-lg xl:text-xl">{{ t('nav.title') }}</span>
        </router-link>

        <!-- Desktop Navigation -->
        <div class="hidden md:flex gap-4 lg:gap-6 xl:gap-8">
          <router-link v-for="item in navigation.filter(nav => nav.href !== '/')" :key="item.name" :to="item.href"
            class="text-muted-foreground hover:text-foreground transition-colors flex items-center gap-2 text-sm lg:text-base xl:text-lg relative"
            :class="{
              'text-foreground': $route.path === item.href
            }">
            <!-- Chat icon with notification badge -->
            <div v-if="item.href === '/chat'" class="relative">
              <MessageSquare class="h-4 w-4" />
              <Badge v-if="totalUnreadMessages > 0"
                class="absolute -top-2 -right-2 h-3.5 w-4 text-xs bg-blue-500 text-white border-0 p-0 flex items-center justify-center">
                {{ totalUnreadMessages > 99 ? '99+' : totalUnreadMessages }}
              </Badge>
            </div>
            <span v-else>{{ item.name }}</span>
            <span v-if="item.href === '/chat'">{{ item.name }}</span>
            <!-- Market preloading indicator -->
            <div v-if="item.href === '/market' && marketPreloader.isPreloading"
              class="w-2 h-2 bg-blue-500 rounded-full animate-pulse"></div>
          </router-link>
        </div>
      </div>

      <!-- Theme Toggle, Language, and Identity -->
      <div class="flex items-center gap-2 lg:gap-4 xl:gap-6">
        <!-- Wallet Balance Display -->
        <!-- <div v-if="auth.isAuthenticated.value" -->
        <!--   class="hidden sm:flex items-center gap-2 px-3 py-1 bg-muted/50 rounded-lg border"> -->
        <!--   <Wallet class="h-4 w-4 text-muted-foreground" /> -->
        <!--   <CurrencyDisplay :balance-msat="totalBalance" /> -->
        <!-- </div> -->

        <!-- Cart Icon with Item Count -->
        <router-link v-if="auth.isAuthenticated.value" to="/cart"
          class="hidden sm:flex items-center gap-2 px-3 py-1 bg-muted/50 rounded-lg border hover:bg-muted/70 transition-colors relative">
          <ShoppingCart class="h-4 w-4 text-muted-foreground" />
          <span class="text-sm font-medium">Cart</span>
          <Badge v-if="cartItemCount > 0"
            class="absolute -top-2 -right-2 h-5 w-5 text-xs bg-blue-500 text-white border-0 p-0 flex items-center justify-center rounded-full">
            {{ cartItemCount > 99 ? '99+' : cartItemCount }}
          </Badge>
        </router-link>

        <!-- Authentication Management -->
        <div class="hidden sm:block">
          <DropdownMenu v-if="auth.isAuthenticated.value">
            <DropdownMenuTrigger asChild>
              <Button variant="ghost" size="sm" class="gap-2 lg:gap-3">
                <User class="h-4 w-4 lg:h-5 lg:w-5" />
                <span class="max-w-24 lg:max-w-32 xl:max-w-40 truncate">{{ auth.userDisplay.value?.name || 'Anonymous'
                  }}</span>
                <Badge variant="secondary" class="text-xs lg:text-sm">Logged In</Badge>
              </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end" class="w-56 lg:w-64">
              <!-- Wallet Balance in Dropdown -->
              <DropdownMenuItem @click="() => router.push('/wallet')" class="gap-2 border-b">
                <Wallet class="h-4 w-4 text-muted-foreground" />
                <CurrencyDisplay :balance-msat="totalBalance" />
              </DropdownMenuItem>

              <DropdownMenuItem @click="openProfileDialog" class="gap-2">
                <User class="h-4 w-4" />
                Profile
              </DropdownMenuItem>
              <DropdownMenuItem v-for="item in userMenuItems" :key="item.href" @click="() => router.push(item.href)"
                class="gap-2">
                <component :is="item.icon === 'Ticket' ? Ticket : item.icon === 'Store' ? Store : Activity"
                  class="h-4 w-4" />
                {{ item.name }}
              </DropdownMenuItem>
              <DropdownMenuSeparator />
              <DropdownMenuItem @click="showLogoutConfirm = true" class="gap-2 text-destructive">
                <LogOut class="h-4 w-4" />
                Logout
              </DropdownMenuItem>
            </DropdownMenuContent>
          </DropdownMenu>

          <Button v-else variant="outline" size="sm" @click="openLoginDialog" class="gap-2 lg:gap-3">
            <User class="h-4 w-4 lg:h-5 lg:w-5" />
            <span class="hidden lg:inline">Login</span>
          </Button>
        </div>

        <!-- Hide theme toggle on mobile -->
        <Button variant="ghost" size="icon" @click="toggleTheme"
          class="hidden sm:inline-flex text-foreground hover:text-foreground/90 hover:bg-accent">
          <Sun v-if="theme === 'dark'" class="h-5 w-5 lg:h-6 lg:w-6" />
          <Moon v-else class="h-5 w-5 lg:h-6 lg:w-6" />
        </Button>

        <!-- Hide language switcher on mobile -->
        <div class="hidden sm:block">
          <LanguageSwitcher />
        </div>

        <!-- Mobile Navigation Icons (only show when authenticated) -->
        <div v-if="auth.isAuthenticated.value" class="md:hidden flex items-center gap-1">
          <!-- Events Button -->
          <router-link to="/events"
            class="relative inline-flex items-center justify-center rounded-md p-2 text-foreground hover:text-foreground/90 hover:bg-accent transition-colors"
            :class="{
              'text-secondary bg-accent': $route.path === '/events'
            }">
            <span class="sr-only">Events</span>
            <Calendar class="h-5 w-5" />
          </router-link>

          <!-- Market Button -->
          <router-link to="/market"
            class="relative inline-flex items-center justify-center rounded-md p-2 text-foreground hover:text-foreground/90 hover:bg-accent transition-colors"
            :class="{
              'text-secondary bg-accent': $route.path.startsWith('/market')
            }">
            <span class="sr-only">Market</span>
            <ShoppingBag class="h-5 w-5" />
            <!-- Market preloading indicator -->
            <div v-if="marketPreloader.isPreloading"
              class="absolute -top-0.5 -right-0.5 w-2 h-2 bg-blue-500 rounded-full animate-pulse"></div>
          </router-link>

          <!-- Chat Button -->
          <router-link to="/chat"
            class="relative inline-flex items-center justify-center rounded-md p-2 text-foreground hover:text-foreground/90 hover:bg-accent transition-colors"
            :class="{
              'text-secondary bg-accent': $route.path === '/chat'
            }">
            <span class="sr-only">Chat</span>
            <MessageSquare class="h-5 w-5" />
            <Badge v-if="totalUnreadMessages > 0"
              class="absolute -top-1 -right-1 h-4 w-4 text-xs bg-blue-500 text-white border-0 p-0 flex items-center justify-center rounded-full">
              {{ totalUnreadMessages > 99 ? '99+' : totalUnreadMessages }}
            </Badge>
          </router-link>
        </div>

        <!-- Mobile menu button -->
        <Button variant="ghost" size="icon" @click="toggleMenu"
          class="md:hidden text-foreground hover:text-foreground/90 hover:bg-accent">
          <span class="sr-only">Open main menu</span>
          <Menu v-if="!isOpen" class="h-5 w-5" />
          <X v-else class="h-5 w-5" />
        </Button>
      </div>
    </div>

    <!-- Mobile menu -->
    <div v-show="isOpen"
      class="absolute left-0 right-0 top-14 lg:top-16 xl:top-20 z-40 border-b bg-background/95 backdrop-blur-sm md:hidden">
      <div class="space-y-1 p-4">
        <!-- Authentication in mobile menu -->
        <div class="mb-4 px-2">
          <Button v-if="!auth.isAuthenticated.value" variant="outline" size="sm" @click="openLoginDialog"
            class="w-full gap-2 min-h-[44px] touch-manipulation">
            <User class="h-4 w-4" />
            Login
          </Button>
          <div v-else class="space-y-2">
            <div class="flex items-center gap-2 px-2 py-1">
              <User class="h-4 w-4" />
              <span class="text-sm font-medium">{{ auth.userDisplay.value?.name || 'Anonymous' }}</span>
              <Badge variant="secondary" class="text-xs ml-auto">Logged In</Badge>
            </div>

            <!-- Mobile Wallet Balance -->
            <button
              @click="() => { router.push('/wallet'); isOpen = false }"
              class="flex items-center justify-between gap-2 px-3 py-2 bg-muted/50 rounded-lg hover:bg-muted/70 transition-colors w-full text-left border border-transparent hover:border-muted-foreground/20"
            >
              <div class="flex items-center gap-2">
                <Wallet class="h-4 w-4 text-muted-foreground" />
                <CurrencyDisplay :balance-msat="totalBalance" />
              </div>
              <ChevronRight class="h-4 w-4 text-muted-foreground" />
            </button>

            <div class="space-y-1">
              <Button variant="ghost" size="sm" @click="openProfileDialog" class="w-full justify-start gap-2">
                <User class="h-4 w-4" />
                Profile
              </Button>
              <Button v-for="item in userMenuItems" :key="item.href" variant="ghost" size="sm"
                @click="() => { router.push(item.href); isOpen = false }" class="w-full justify-start gap-2">
                <component :is="item.icon === 'Ticket' ? Ticket : item.icon === 'Store' ? Store : Activity"
                  class="h-4 w-4" />
                {{ item.name }}
              </Button>
              <Button variant="ghost" size="sm" @click="showLogoutConfirm = true"
                class="w-full justify-start gap-2 text-destructive hover:text-destructive/90 hover:bg-destructive/10">
                <LogOut class="h-4 w-4" />
                Logout
              </Button>
            </div>
          </div>
        </div>

        <!-- Add theme and language toggles to mobile menu -->
        <div class="flex items-center justify-between mb-4 px-2 border-t pt-4">
          <Button variant="ghost" size="icon" @click="toggleTheme"
            class="text-foreground hover:text-foreground/90 hover:bg-accent">
            <Sun v-if="theme === 'dark'" class="h-5 w-5" />
            <Moon v-else class="h-5 w-5" />
          </Button>
          <LanguageSwitcher />
        </div>

        <!-- Navigation routes removed from mobile dropdown for better UX -->
        <!-- Routes are now available as icons in the top navigation -->
      </div>
    </div>

    <!-- Login Dialog -->
    <LoginDialog v-model:is-open="showLoginDialog" />

    <!-- Profile Dialog -->
    <ProfileDialog v-model:is-open="showProfileDialog" />

    <!-- Logout Confirm Dialog -->
    <LogoutConfirmDialog v-model:is-open="showLogoutConfirm" variant="ghost" size="sm"
      class="w-full justify-start gap-2" @confirm="handleLogout">
      <LogOut class="h-4 w-4" />
      Logout
    </LogoutConfirmDialog>
  </nav>
</template>
