"use client";

import { useState } from "react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { cn } from "@/shared/lib/utils";
import { Button } from "@/presentation/components/ui/button";
import { Badge } from "@/presentation/components/ui/badge";
import { Avatar, AvatarFallback } from "@/presentation/components/ui/avatar";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuRadioGroup,
  DropdownMenuRadioItem,
  DropdownMenuSeparator,
  DropdownMenuSub,
  DropdownMenuSubContent,
  DropdownMenuSubTrigger,
  DropdownMenuTrigger,
} from "@/presentation/components/ui/dropdown-menu";
import {
  Tooltip,
  TooltipContent,
  TooltipTrigger,
} from "@/presentation/components/ui/tooltip";
import {
  LayoutDashboard,
  Building2,
  CreditCard,
  Search,
  ChevronLeft,
  ChevronRight,
  LogOut,
  User,
  Shield,
  Car,
  MapPin,
  Menu,
  X,
  Activity,
  MessagesSquare,
  Languages,
  Book,
  Radio,
  Wrench,
  ScanLine,
  Nfc,
  HeartPulse,
  Cable,
  Link2,
  SlidersHorizontal,
} from "lucide-react";
import { NotificationBell } from "@/presentation/components/layout/notification-bell";
import { useAuth } from "@/presentation/hooks/use-auth";
import { useSupportUnreadCount } from "@/presentation/hooks/use-support-unread-count";
import { usePageHeaderValue } from "@/presentation/hooks/use-page-header";
import { ROUTES, ROUTE_PERMISSION, ROUTE_PERMISSION_ANY } from "@/shared/constants";
import { useT, useLocale } from "@/shared/i18n/client";
import { LOCALES, LOCALE_LABELS, type Locale } from "@/shared/i18n/config";
import { setLocaleAction } from "@/shared/i18n/actions";

interface NavItem {
  label: string;
  icon: React.ComponentType<{ className?: string }>;
  href: string;
  badge?: number | string;
  category?: string;
}

interface AdminLayoutProps {
  children: React.ReactNode;
}

export default function AdminLayout({ children }: AdminLayoutProps) {
  const pathname = usePathname();
  const { user, logout, hasPermission } = useAuth();
  const pageHeader = usePageHeaderValue();
  const t = useT();
  const locale = useLocale();
  const [collapsed, setCollapsed] = useState(false);
  const [mobileOpen, setMobileOpen] = useState(false);
  const supportUnread = useSupportUnreadCount(hasPermission("tickets.view"));

  const navItems: NavItem[] = [
    { label: t.nav.overview, icon: LayoutDashboard, href: ROUTES.dashboard, category: t.navCategories.main },
    { label: t.nav.companies, icon: Building2, href: ROUTES.companies, category: t.navCategories.management },
    { label: t.nav.vehicles, icon: Car, href: ROUTES.vehicles, category: t.navCategories.technical },
    { label: t.nav.sites, icon: MapPin, href: ROUTES.sites, category: t.navCategories.technical },
    { label: t.nav.subscriptions, icon: CreditCard, href: ROUTES.subscriptions, category: t.navCategories.commercial },
    { label: t.nav.tickets, icon: MessagesSquare, href: ROUTES.support, category: t.navCategories.management, badge: supportUnread || undefined },
    { label: t.nav.telematics, icon: Radio, href: ROUTES.telematics, category: t.navCategories.technical },
    { label: t.nav.installations, icon: Wrench, href: ROUTES.installations, category: t.navCategories.technical },
    { label: t.nav.antai, icon: ScanLine, href: ROUTES.antai, category: t.navCategories.technical },
    { label: t.nav.rfidCards, icon: Nfc, href: ROUTES.rfidCards, category: t.navCategories.technical },
    { label: t.nav.health, icon: HeartPulse, href: ROUTES.health, category: t.navCategories.system },
    { label: t.nav.activityLogs, icon: Activity, href: ROUTES.activityLogs, category: t.navCategories.system },
    { label: t.nav.helpCenter, icon: Book, href: ROUTES.helpCenter, category: t.navCategories.system },
    { label: t.nav.internalUsers, icon: Shield, href: ROUTES.internalUsers, category: t.navCategories.administration },
    { label: t.nav.integrations, icon: Cable, href: ROUTES.integrations, category: t.navCategories.technical },
    { label: t.nav.anomalyRules, icon: SlidersHorizontal, href: ROUTES.anomalyRules, category: t.navCategories.technical },
    //{ label: t.nav.integrationConnections, icon: Link2, href: ROUTES.integrationConnections, category: t.navCategories.technical },
  ];

  const categories = [
    t.navCategories.main,
    t.navCategories.management,
    t.navCategories.commercial,
    t.navCategories.technical,
    t.navCategories.system,
    t.navCategories.administration,
  ];

  const SidebarContent = () => (
    <div className="flex flex-col h-full">
      {/* Logo */}
      <div className={cn(
        "flex items-center gap-3 px-4 py-5 border-b border-white/10",
        collapsed && "justify-center px-3"
      )}>
        <div className="flex-shrink-0 w-8 h-8 bg-blue-500 rounded-lg flex items-center justify-center shadow-lg">
          <Car className="w-4 h-4 text-white" />
        </div>
        {!collapsed && (
          <div className="min-w-0">
            <div className="text-white font-bold text-base leading-tight tracking-tight">{t.auth.appName}</div>
            <div className="text-blue-300 text-xs font-medium">{t.account.defaultName}</div>
          </div>
        )}
      </div>

      {/* Navigation */}
      <nav className="flex-1 overflow-y-auto py-4 px-2 space-y-0.5">
        {categories.map((category) => {
          const items = navItems.filter(
            (item) =>
              item.category === category &&
              ((!ROUTE_PERMISSION[item.href] || hasPermission(ROUTE_PERMISSION[item.href])) ||
                (ROUTE_PERMISSION_ANY[item.href] ?? []).some((code) => hasPermission(code)))
          );
          if (items.length === 0) return null;
          return (
            <div key={category} className="mb-3">
              {!collapsed && (
                <div className="px-3 mb-1.5">
                  <span className="text-[10px] font-semibold uppercase tracking-widest text-blue-300/60">
                    {category}
                  </span>
                </div>
              )}
              {items.map((item) => {
                const isActive = pathname === item.href || (item.href !== ROUTES.dashboard && pathname.startsWith(item.href));
                const Icon = item.icon;

                if (collapsed) {
                  return (
                    <Tooltip key={item.href} delayDuration={0}>
                      <TooltipTrigger asChild>
                        <Link href={item.href}>
                          <div className={cn(
                            "relative flex items-center justify-center w-10 h-10 mx-auto rounded-lg transition-all duration-150 cursor-pointer",
                            isActive
                              ? "bg-blue-500 text-white shadow-lg shadow-blue-500/30"
                              : "text-blue-200/70 hover:bg-white/10 hover:text-white"
                          )}>
                            <Icon className="w-4.5 h-4.5" />
                            {item.badge && (
                              <span className="absolute -top-0.5 -right-0.5 w-4 h-4 bg-red-500 text-white text-[9px] font-bold rounded-full flex items-center justify-center">
                                {typeof item.badge === "number" && item.badge > 9 ? "9+" : item.badge}
                              </span>
                            )}
                          </div>
                        </Link>
                      </TooltipTrigger>
                      <TooltipContent side="right" className="font-medium">
                        {item.label}
                        {item.badge && <span className="ml-2 text-red-400">({item.badge})</span>}
                      </TooltipContent>
                    </Tooltip>
                  );
                }

                return (
                  <Link key={item.href} href={item.href}>
                    <div className={cn(
                      "flex items-center gap-3 px-3 py-2.5 rounded-lg transition-all duration-150 cursor-pointer group",
                      isActive
                        ? "bg-blue-500 text-white shadow-md shadow-blue-500/25"
                        : "text-blue-100/70 hover:bg-white/10 hover:text-white"
                    )}>
                      <Icon className={cn(
                        "w-4 h-4 flex-shrink-0",
                        isActive ? "text-white" : "text-blue-300/80 group-hover:text-white"
                      )} />
                      <span className="text-sm font-medium flex-1 truncate">{item.label}</span>
                      {item.badge && (
                        <Badge className={cn(
                          "text-[10px] px-1.5 py-0 h-4 font-bold",
                          isActive ? "bg-white/20 text-white border-0" : "bg-red-500 text-white border-0"
                        )}>
                          {item.badge}
                        </Badge>
                      )}
                    </div>
                  </Link>
                );
              })}
            </div>
          );
        })}
      </nav>

      {/* User Profile */}
      <div className={cn(
        "border-t border-white/10 p-3",
        collapsed ? "flex justify-center" : ""
      )}>
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <button className={cn(
              "flex items-center gap-3 rounded-lg p-2 w-full transition-colors hover:bg-white/10",
              collapsed && "w-10 justify-center"
            )}>
              <Avatar className="w-8 h-8 flex-shrink-0">
                <AvatarFallback className="bg-blue-500 text-white text-xs font-bold">
                  {user?.name ? `${user.name.split(" ").map((w: string) => w[0]).join("").slice(0, 2)}` : "SA"}
                </AvatarFallback>
              </Avatar>
              {!collapsed && (
                <div className="flex-1 min-w-0 text-left">
                  <div className="text-white text-sm font-semibold truncate">
                    {user?.name || t.account.defaultName}
                  </div>
                  <div className="text-blue-300 text-xs truncate">{user?.email ?? t.account.defaultEmail}</div>
                </div>
              )}
            </button>
          </DropdownMenuTrigger>
          <DropdownMenuContent side="right" align="end" className="w-52">
            <DropdownMenuLabel>{t.account.myAccount}</DropdownMenuLabel>
            <DropdownMenuSeparator />
            <DropdownMenuItem>
              <User className="w-4 h-4 mr-2" />
              {t.account.profile}
            </DropdownMenuItem>
            <DropdownMenuItem>
              <Shield className="w-4 h-4 mr-2" />
              {t.account.security}
            </DropdownMenuItem>
            <DropdownMenuSub>
              <DropdownMenuSubTrigger>
                <Languages className="w-4 h-4 mr-2" />
                {LOCALE_LABELS[locale]}
              </DropdownMenuSubTrigger>
              <DropdownMenuSubContent>
                <DropdownMenuRadioGroup
                  value={locale}
                  onValueChange={(v) => setLocaleAction(v as Locale)}
                >
                  {LOCALES.map((l) => (
                    <DropdownMenuRadioItem key={l} value={l}>
                      {LOCALE_LABELS[l]}
                    </DropdownMenuRadioItem>
                  ))}
                </DropdownMenuRadioGroup>
              </DropdownMenuSubContent>
            </DropdownMenuSub>
            <DropdownMenuSeparator />
            <DropdownMenuItem className="text-red-600" onClick={() => logout()}>
              <LogOut className="w-4 h-4 mr-2" />
              {t.account.logout}
            </DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      </div>
    </div>
  );

  return (
    <div className="flex h-screen bg-background overflow-hidden">
      {/* Desktop Sidebar */}
      <aside className={cn(
        "hidden lg:flex flex-col flex-shrink-0 transition-all duration-300 ease-in-out",
        "bg-[#1E3A5F]",
        collapsed ? "w-16" : "w-60"
      )}>
        <SidebarContent />
      </aside>

      {/* Mobile Sidebar Overlay */}
      {mobileOpen && (
        <div className="lg:hidden fixed inset-0 z-50 flex">
          <div className="fixed inset-0 bg-black/60 backdrop-blur-sm" onClick={() => setMobileOpen(false)} />
          <aside className="relative flex flex-col w-64 bg-[#1E3A5F] shadow-2xl z-10">
            <button
              onClick={() => setMobileOpen(false)}
              className="absolute top-4 right-4 text-white/60 hover:text-white"
            >
              <X className="w-5 h-5" />
            </button>
            <SidebarContent />
          </aside>
        </div>
      )}

      {/* Main Content */}
      <div className="flex-1 flex flex-col min-w-0 overflow-hidden">
        {/* Top Header */}
        <header className="flex-shrink-0 bg-card border-b border-border px-4 lg:px-6 py-3.5 flex items-center gap-4">
          {/* Mobile menu button */}
          <button
            className="lg:hidden p-1.5 rounded-md hover:bg-muted text-muted-foreground"
            onClick={() => setMobileOpen(true)}
          >
            <Menu className="w-5 h-5" />
          </button>

          {/* Collapse toggle (desktop) */}
          <button
            className="hidden lg:flex p-1.5 rounded-md hover:bg-muted text-muted-foreground transition-colors"
            onClick={() => setCollapsed(!collapsed)}
          >
            {collapsed ? <ChevronRight className="w-4 h-4" /> : <ChevronLeft className="w-4 h-4" />}
          </button>

          {/* Page title */}
          <div className="flex-1 min-w-0">
            {pageHeader && (
              <div>
                <h1 className="text-lg font-bold text-foreground truncate">{pageHeader.title}</h1>
                {pageHeader.subtitle && <p className="text-xs text-muted-foreground truncate">{pageHeader.subtitle}</p>}
              </div>
            )}
          </div>

          {/* Search */}
          <div className="hidden md:flex items-center gap-2 bg-muted rounded-lg px-3 py-2 w-64">
            <Search className="w-4 h-4 text-muted-foreground flex-shrink-0" />
            <input
              type="text"
              placeholder={t.account.searchPlaceholder}
              className="bg-transparent text-sm text-foreground placeholder:text-muted-foreground outline-none flex-1 min-w-0"
            />
            <kbd className="text-[10px] text-muted-foreground bg-background border border-border rounded px-1.5 py-0.5 font-mono">
              ⌘K
            </kbd>
          </div>

          {/* Notifications */}
          <NotificationBell />

          {/* Avatar */}
          <Avatar className="w-8 h-8 cursor-pointer">
            <AvatarFallback className="bg-blue-500 text-white text-xs font-bold">SA</AvatarFallback>
          </Avatar>
        </header>

        {/* Page Content */}
        <main className="flex-1 overflow-y-auto">
          {children}
        </main>
      </div>
    </div>
  );
}
