import { useState } from "react";
import { useAuth } from "@/hooks/use-auth";
import { useLanguage } from "@/hooks/use-language";
import { Link, useLocation } from "wouter";
import { Button } from "@/components/ui/button";
import { useNotifications } from "@/components/notification/notification-provider";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuGroup,
} from "@/components/ui/dropdown-menu";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Calendar, Camera, Home, Menu, Users, ListPlus, Newspaper, Image, Video, UserCog, Bell, Sun, Moon, Settings, HelpCircle, MessageSquare, ChartBar, X, Code } from "lucide-react";
import { useTheme } from "@/components/theme-provider";
import { format } from "date-fns";
import { useSettings } from "@/hooks/use-settings";

export default function Navbar() {
  const [location] = useLocation();
  const { user, logoutMutation } = useAuth();
  const { notifications, markAsRead, removeNotification } = useNotifications();
  const { theme, setTheme } = useTheme();
  const { language, setLanguage, t } = useLanguage();
  const { settings } = useSettings();

  // Helper function to get user's initial safely
  const getUserInitial = (name: string | null | undefined) => {
    if (!name) return '?';
    const trimmedName = name.trim();
    return trimmedName ? trimmedName.charAt(0).toUpperCase() : '?';
  };

  // Public navigation items with bilingual labels
  const publicNavItems = [
    { href: "/", label: t("Home", "الرئيسية"), icon: Home },
    { href: "/sessions", label: t("Program", "البرنامج"), icon: Calendar },
    { href: "/speakers", label: t("Speakers", "المتحدثون"), icon: Users },
    { href: "/gallery", label: t("Gallery", "معرض الصور"), icon: Camera },
    { href: "/news", label: t("News", "الأخبار"), icon: Newspaper },
    { href: "/live-streams", label: t("Live Streams", "البث المباشر"), icon: Video },
  ];

  // Management navigation groups with bilingual labels
  const managementGroups = {
    events: {
      label: t("Events", "الفعاليات"),
      items: [
        { href: "/manage/events", label: t("Events", "الفعاليات"), icon: Calendar, roles: ['admin', 'organizer'] },
        { href: "/manage/sessions", label: t("Sessions", "الجلسات"), icon: ListPlus, roles: ['admin', 'organizer'] },
        { href: "/manage/speakers", label: t("Speakers", "المتحدثون"), icon: Users, roles: ['admin', 'organizer'] },
      ],
    },
    content: {
      label: t("Content", "المحتوى"),
      items: [
        { href: "/manage/news", label: t("News", "الأخبار"), icon: Newspaper, roles: ['admin', 'organizer'] },
        { href: "/manage/media", label: t("Media", "الوسائط"), icon: Image, roles: ['admin', 'organizer'] },
        { href: "/manage/questions", label: t("Questions", "الأسئلة"), icon: HelpCircle, roles: ['admin', 'moderator'] },
        { href: "/manage/transcriptions", label: t("Transcriptions", "النسخ"), icon: MessageSquare, roles: ['admin', 'moderator'] },
        { href: "/manage/polls", label: t("Polls", "الاستطلاعات"), icon: ChartBar, roles: ['admin', 'organizer'] },
        { href: "/manage/notifications", label: t("Notifications", "الإشعارات"), icon: Bell, roles: ['admin', 'organizer'] },
        { href: "/stream-test", label: t("Stream Test", "اختبار البث"), icon: Video, roles: ['admin', 'organizer'] },
      ],
    },
    admin: {
      label: t("Admin", "المشرف"),
      items: [
        { href: "/manage/users", label: t("Users", "المستخدمون"), icon: UserCog, roles: ['admin'] },
        { href: "/manage/settings", label: t("Settings", "الإعدادات"), icon: Settings, roles: ['admin'] },
        { href: "/manage/api-docs", label: t("API Documentation", "توثيق API"), icon: Code, roles: ['admin'] },
      ],
    },
  };

  if (!user) return null;

  const unreadCount = notifications.filter(n => !n.read).length;

  return (
    <nav className={`border-b ${language === 'ar' ? 'rtl' : 'ltr'}`}>
      <div className="container mx-auto px-4 h-16 flex items-center justify-between">
        <Link href="/" className="font-bold text-xl">
          {language === 'ar' ? settings?.logoTextAr : settings?.logoText}
        </Link>

        {/* Desktop Navigation */}
        <div className="hidden md:flex items-center space-x-4">
          {/* Public Routes */}
          {publicNavItems.map((item) => (
            <Link key={item.href} href={item.href}>
              <Button
                variant={location === item.href ? "default" : "ghost"}
                className="flex items-center gap-2"
              >
                <item.icon className="h-4 w-4" />
                {item.label}
              </Button>
            </Link>
          ))}

          <div className="flex items-center space-x-2">
            {/* Theme Toggle */}
            <Button
              variant="ghost"
              size="icon"
              onClick={() => setTheme(theme === "light" ? "dark" : "light")}
            >
              {theme === "light" ? (
                <Moon className="h-4 w-4" />
              ) : (
                <Sun className="h-4 w-4" />
              )}
            </Button>

            {/* Language Switcher */}
            <Button
              variant="ghost"
              size="icon"
              onClick={() => setLanguage(language === "en" ? "ar" : "en")}
              className="font-medium"
            >
              <span className="text-sm">{language === "en" ? "ع" : "EN"}</span>
            </Button>

            {/* Notification Dropdown */}
            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <Button
                  variant="ghost"
                  size="icon"
                  className="relative"
                >
                  <Bell className="h-4 w-4" />
                  {unreadCount > 0 && (
                    <span className="absolute -top-1 -right-1 bg-red-500 text-white text-xs rounded-full w-4 h-4 flex items-center justify-center">
                      {unreadCount}
                    </span>
                  )}
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent align="end" className="w-80">
                <DropdownMenuLabel>{t("Notifications", "الإشعارات")}</DropdownMenuLabel>
                <DropdownMenuSeparator />

                {notifications.length > 0 ? (
                  <div className="max-h-[300px] overflow-y-auto">
                    {notifications.map((notification) => (
                      <div
                        key={notification.id}
                        className="p-3 hover:bg-accent cursor-pointer relative group"
                        onClick={() => {
                          markAsRead(notification.id);
                          if (notification.url) {
                            window.location.href = notification.url;
                          }
                        }}
                      >
                        <Button
                          variant="ghost"
                          size="icon"
                          className="absolute right-2 top-2 opacity-0 group-hover:opacity-100"
                          onClick={(e) => {
                            e.stopPropagation();
                            removeNotification(notification.id);
                          }}
                        >
                          <X className="h-4 w-4" />
                        </Button>
                        <div className="font-medium">{notification.title}</div>
                        <div className="text-sm text-muted-foreground">{notification.body}</div>
                        <div className="text-xs text-muted-foreground mt-1">
                          {format(new Date(notification.timestamp), 'MMM d, yyyy HH:mm')}
                        </div>
                        {!notification.read && (
                          <div className="absolute left-0 top-0 w-1 h-full bg-red-500" />
                        )}
                      </div>
                    ))}
                  </div>
                ) : (
                  <div className="p-4 text-center text-sm text-muted-foreground">
                    {t("No new notifications", "لا يوجد إشعارات جديدة")}
                  </div>
                )}
              </DropdownMenuContent>
            </DropdownMenu>

            {/* Profile Dropdown */}
            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <Button variant="ghost" className="relative h-8 w-8 rounded-full">
                  <Avatar className="h-8 w-8">
                    <AvatarImage src={user.profileImage || undefined} alt={user.name || 'User'} />
                    <AvatarFallback>{getUserInitial(user.name)}</AvatarFallback>
                  </Avatar>
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent align="end">
                <DropdownMenuLabel>{t("My Account", "حسابي")}</DropdownMenuLabel>
                <DropdownMenuSeparator />

                {/* Management Groups */}
                {Object.entries(managementGroups).map(([key, group]) => {
                  // Get items that the user has access to based on their role
                  const accessibleItems = group.items.filter(item =>
                    item.roles && item.roles.includes(user.role)
                  );

                  // Only show the group if there are accessible items
                  return accessibleItems.length > 0 ? (
                    <DropdownMenuGroup key={key}>
                      <DropdownMenuLabel>{group.label}</DropdownMenuLabel>
                      {accessibleItems.map((item) => (
                        <DropdownMenuItem key={item.href} asChild>
                          <Link href={item.href}>
                            <span className="flex items-center gap-2">
                              <item.icon className="h-4 w-4" />
                              {item.label}
                            </span>
                          </Link>
                        </DropdownMenuItem>
                      ))}
                      <DropdownMenuSeparator />
                    </DropdownMenuGroup>
                  ) : null;
                })}

                <DropdownMenuItem
                  onClick={() => logoutMutation.mutate()}
                  className="text-red-600"
                >
                  <span className="flex items-center gap-2">
                    {t("Logout", "تسجيل الخروج")}
                  </span>
                </DropdownMenuItem>
              </DropdownMenuContent>
            </DropdownMenu>
          </div>
        </div>

        {/* Mobile Navigation */}
        <DropdownMenu>
          <DropdownMenuTrigger asChild className="md:hidden">
            <Button variant="ghost" size="icon">
              <Menu className="h-5 w-5" />
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end" className="w-64">
            {/* Profile Section */}
            <div className="flex items-center space-x-2 p-2">
              <Avatar className="h-8 w-8">
                <AvatarImage src={user.profileImage || undefined} alt={user.name || 'User'} />
                <AvatarFallback>{getUserInitial(user.name)}</AvatarFallback>
              </Avatar>
              <div className="flex flex-col">
                <span className="text-sm font-medium">{user.name || 'User'}</span>
                <span className="text-xs text-muted-foreground">{user.email}</span>
              </div>
            </div>
            <DropdownMenuSeparator />

            {/* Theme and Notifications for Mobile */}
            <div className="flex items-center justify-between px-2 py-1.5">
              <Button
                variant="ghost"
                size="icon"
                onClick={() => setTheme(theme === "light" ? "dark" : "light")}
              >
                {theme === "light" ? (
                  <Moon className="h-4 w-4" />
                ) : (
                  <Sun className="h-4 w-4" />
                )}
              </Button>
              <Button
                variant="ghost"
                size="icon"
                onClick={() => setLanguage(language === "en" ? "ar" : "en")}
                className="font-medium"
              >
                <span className="text-sm">{language === "en" ? "ع" : "EN"}</span>
              </Button>
              <Button
                variant="ghost"
                size="icon"
                className="relative"
              >
                <Bell className="h-4 w-4" />
                {unreadCount > 0 && (
                  <span className="absolute -top-1 -right-1 bg-red-500 text-white text-xs rounded-full w-4 h-4 flex items-center justify-center">
                    {unreadCount}
                  </span>
                )}
              </Button>
            </div>
            <DropdownMenuSeparator />

            {/* Public Routes */}
            <DropdownMenuGroup>
              {publicNavItems.map((item) => (
                <DropdownMenuItem key={item.href} asChild>
                  <Link href={item.href}>
                    <span className="flex items-center gap-2">
                      <item.icon className="h-4 w-4" />
                      {item.label}
                    </span>
                  </Link>
                </DropdownMenuItem>
              ))}
            </DropdownMenuGroup>

            <DropdownMenuSeparator />

            {/* Management Groups for Mobile */}
            {Object.entries(managementGroups).map(([key, group]) => {
              // Get items that the user has access to based on their role
              const accessibleItems = group.items.filter(item =>
                item.roles && item.roles.includes(user.role)
              );

              // Only show the group if there are accessible items
              return accessibleItems.length > 0 ? (
                <DropdownMenuGroup key={key}>
                  <DropdownMenuLabel>{group.label}</DropdownMenuLabel>
                  {accessibleItems.map((item) => (
                    <DropdownMenuItem key={item.href} asChild>
                      <Link href={item.href}>
                        <span className="flex items-center gap-2">
                          <item.icon className="h-4 w-4" />
                          {item.label}
                        </span>
                      </Link>
                    </DropdownMenuItem>
                  ))}
                  <DropdownMenuSeparator />
                </DropdownMenuGroup>
              ) : null;
            })}

            {/* Logout */}
            <DropdownMenuItem
              onClick={() => logoutMutation.mutate()}
              className="text-red-600"
            >
              <span className="flex items-center gap-2">
                {t("Logout", "تسجيل الخروج")}
              </span>
            </DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      </div>
    </nav>
  );
}