<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, BarChart3 } 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/useAuth'
import { useMarketPreloader } from '@/composables/useMarketPreloader'
import { useMarketStore } from '@/stores/market'
import { nostrChat } from '@/composables/useNostrChat'
import { useModularNavigation } from '@/composables/useModularNavigation'

interface NavigationItem {
  name: string
  href: string
}

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

// Compute total wallet balance
const totalBalance = computed(() => {
  if (!auth.currentUser.value?.wallets) return 0

  return auth.currentUser.value.wallets.reduce((total, wallet) => {
    return total + (wallet.balance_msat || 0)
  }, 0)
})

// Compute total unread messages (reactive)
const totalUnreadMessages = computed(() => {
  return nostrChat.totalUnreadCount.value
})

// 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" :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 -->
              <div class="flex items-center gap-2 px-2 py-1.5 text-sm border-b">
                <Wallet class="h-4 w-4 text-muted-foreground" />
                <CurrencyDisplay :balance-msat="totalBalance" />
              </div>

              <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 === 'BarChart3' ? BarChart3 : 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 Chat Button (only show when authenticated) -->
        <router-link v-if="auth.isAuthenticated.value" to="/chat" 
          class="md:hidden relative inline-flex items-center justify-center rounded-md p-2 text-foreground hover:text-foreground/90 hover:bg-accent transition-colors">
          <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>

        <!-- 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 -->
            <div class="flex items-center gap-2 px-2 py-1 bg-muted/50 rounded-lg">
              <Wallet class="h-4 w-4 text-muted-foreground" />
              <CurrencyDisplay :balance-msat="totalBalance" />
            </div>

            <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)"
                class="w-full justify-start gap-2">
                <component :is="item.icon === 'Ticket' ? Ticket : item.icon === 'BarChart3' ? BarChart3 : 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>

        <router-link v-for="item in navigation.filter(nav => nav.href !== '/chat')" :key="item.name" :to="item.href"
          class="flex items-center gap-2 px-3 py-2 text-base font-medium text-muted-foreground hover:text-foreground transition-colors relative"
          :class="{
            'text-foreground': $route.path === item.href
          }" @click="isOpen = false">
          <span>{{ 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>

    <!-- 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>
