"use client";

import {
  Collapsible,
  CollapsibleContent,
  CollapsibleTrigger,
} from "@/components/ui/collapsible";
import {
  Sidebar,
  SidebarContent,
  SidebarGroup,
  SidebarGroupContent,
  SidebarGroupLabel,
  SidebarHeader,
  SidebarMenu,
  SidebarMenuButton,
  SidebarMenuItem,
  useSidebar,
} from "@/components/ui/sidebar";
import { useProject } from "@/contexts/project-context";
import { useSettingsContext } from "@/contexts/settings-context";
import {
  useFilteredNavItems,
  useFilteredSections,
} from "@/hooks/use-filtered-sidebar-items";
import { Link, usePathname } from "@/i18n/routing";
import { SidebarPermissionKey } from "@/lib/sidebar-permissions";
import { cn } from "@/lib/utils";
import {
  BarChart3,
  Bell,
  Calendar,
  ChevronLeft,
  ChevronRight,
  ChevronUp,
  Clock,
  Earth,
  FileText,
  FolderKanban,
  Home,
  Key,
  Megaphone,
  Newspaper,
  Settings,
  Shield,
  Users
} from "lucide-react";
import { TrashIcon } from "@/components/icons/dashboard";
import { useLocale, useTranslations } from "next-intl";
import * as React from "react";

type NavItem = {
  title: string;
  href: string;
  icon: React.ComponentType<{ className?: string }>;
  translationKey: string;
  permissionKey?: SidebarPermissionKey;
};

type NavSection = {
  title: string;
  translationKey: string;
  items: NavItem[];
  collapsible?: boolean;
};

export function AppSidebar() {
  const t = useTranslations();
  const locale = useLocale();
  const pathname = usePathname();
  const { state, isMobile, toggleSidebar } = useSidebar();
  const { projectName, projectNameTranslations, projectProgress, projectId } = useProject();
  const { dashboardLogo, dashboardIcon, primaryColor, dashboardName, isLoading: settingsLoading } = useSettingsContext();

  const displayProjectName = projectNameTranslations?.[locale as "ar" | "en"] || projectName;
  const hasSelectedProject = projectId.trim().length > 0;

  // Detect RTL based on locale
  const isRTL = locale === "ar";

  // Use cached logo/name/aspect from localStorage to prevent flicker on refresh
  const [cachedLogo, setCachedLogo] = React.useState<string | null>(null);
  const [cachedName, setCachedName] = React.useState<string | null>(null);

  // Resolve: prefer live settings, fall back to cached
  const resolvedLogo = dashboardLogo || cachedLogo;
  const resolvedName = dashboardName || cachedName;

  const [isWideLogo, setIsWideLogo] = React.useState(false);

  // Load cached values from localStorage only on client-side to avoid hydration mismatch
  React.useEffect(() => {
    if (typeof window !== "undefined") {
      setCachedLogo(localStorage.getItem("dashboard_logo"));
      setCachedName(localStorage.getItem("dashboard_name"));
      setIsWideLogo(localStorage.getItem("dashboard_logo_wide") === "true");
    }
  }, []);

  // If we have a cached logo URL, assume loaded (browser HTTP cache + preload should have it)
  // This avoids showing the skeleton for even a single frame on refresh
  const [logoLoaded, setLogoLoaded] = React.useState(false);
  const prevLogoRef = React.useRef(resolvedLogo);

  // Only reset loaded state when logo URL actually changes to a different URL
  React.useEffect(() => {
    if (resolvedLogo && resolvedLogo !== prevLogoRef.current) {
      prevLogoRef.current = resolvedLogo;
      setLogoLoaded(false);
    }
  }, [resolvedLogo]);

  const handleImageLoad = (e: React.SyntheticEvent<HTMLImageElement>) => {
    const { naturalWidth, naturalHeight } = e.currentTarget;
    if (naturalHeight > 0) {
      const ratio = naturalWidth / naturalHeight;
      const wide = ratio > 1.2;
      setIsWideLogo(wide);
      localStorage.setItem("dashboard_logo_wide", String(wide));
    }
    setLogoLoaded(true);
  };

  const handleImageError = () => {
    setLogoLoaded(false);
    // Clear stale cached logo
    localStorage.removeItem("dashboard_logo");
    localStorage.removeItem("dashboard_logo_wide");
  };

  const mainNavItems: NavItem[] = [
    {
      title: "Dashboard",
      href: "/",
      icon: Home,
      translationKey: "sidebar.dashboard",
      permissionKey: "dashboard",
    },
    {
      title: "Projects",
      href: "/projects",
      icon: FolderKanban,
      translationKey: "sidebar.projects",
      permissionKey: "projects",
    },
    {
      title: "Approvals",
      href: "/approvals",
      icon: Bell,
      translationKey: "sidebar.approvals",
      permissionKey: "approvals",
    },

    // {
    //   title: "Notifications",
    //   href: "/notifications",
    //   icon: Bell,
    //   translationKey: "sidebar.notifications",
    //   permissionKey: "notifications",
    // },
  ];

  const currentProjectSection: NavSection | null = hasSelectedProject
    ? {
      title: "Current Project",
      translationKey: "sidebar.currentProject",
      collapsible: true,
      items: [
        {
          title: "Project Details",
          href: `/projects/${projectId}`,
          icon: Calendar,
          translationKey: "sidebar.timeline",
          permissionKey: "timeline",
        },
        {
          title: "Files",
          href: "/files",
          icon: FileText,
          translationKey: "sidebar.files",
          permissionKey: "files",
        },
        {
          title: "Activity Log",
          href: "/activity",
          icon: Clock,
          translationKey: "sidebar.activityLog",
          permissionKey: "activity",
        },
        {
          title: "Reports",
          href: "/reports",
          icon: BarChart3,
          translationKey: "sidebar.reports",
          permissionKey: "reports",
        },
        {
          title: "Social Media",
          href: "/social-media",
          icon: Earth,
          translationKey: "sidebar.socialMedia",
          permissionKey: "socialMedia",
        },
        {
          title: "Ads",
          href: "/ads",
          icon: Megaphone,
          translationKey: "sidebar.ads",
          permissionKey: "ads",
        },
        {
          title: "News",
          href: "/news",
          icon: Newspaper,
          translationKey: "sidebar.news",
          permissionKey: "news",
        },
        {
          title: "Articles",
          href: "/articles",
          icon: FileText,
          translationKey: "sidebar.articles",
          permissionKey: "articles",
        },
      ],
    }
    : null;

  const sections: NavSection[] = [
    {
      title: "System Management",
      translationKey: "sidebar.systemManagement",
      collapsible: true,
      items: [
        {
          title: "Roles",
          href: "/roles",
          icon: Shield,
          translationKey: "sidebar.roles",
          permissionKey: "roles",
        },
        {
          title: "Permissions",
          href: "/permissions",
          icon: Key,
          translationKey: "sidebar.permissions",
          permissionKey: "permissions",
        },
        {
          title: "Deleted Projects Log",
          href: "/projects/deletion-logs",
          icon: TrashIcon,
          translationKey: "sidebar.deletedProjectsLog",
          permissionKey: "projectDeletionLogs",
        },
        {
          title: "Users",
          href: "/users",
          icon: Users,
          translationKey: "sidebar.users",
          permissionKey: "users",
        },
        {
          title: "Settings",
          href: "/settings",
          icon: Settings,
          translationKey: "settings.title",
          permissionKey: "settings",
        },
      ],
    },
    ...(currentProjectSection ? [currentProjectSection] : []),
  ];

  // Filter nav items and sections based on user permissions
  const filteredMainNav = useFilteredNavItems(mainNavItems);
  const filteredSections = useFilteredSections(sections);

  const isActive = (href: string) => {
    // Exact match for home page
    if (href === "/") {
      return pathname === "/";
    }

    // For other pages, match exact path or child paths
    return pathname === href || pathname.startsWith(`${href}/`);
  };

  const handleNavClick = () => {
    if (isMobile) {
      toggleSidebar();
    }
  };

  return (
    <Sidebar
      collapsible="icon"
      side={isRTL ? "right" : "left"}
      className="border-none z-20"
    >
      {/* Collapse Toggle Button - Positioned absolutely as per Figma */}
      {!isMobile && (
        <button
          onClick={toggleSidebar}
          className={cn(
            "absolute flex items-center justify-center z-50 transition-all duration-200",
            isRTL
              ? state === "expanded"
                ? "-left-3 top-12"
                : "right-8 top-12"
              : state === "expanded"
                ? "-right-3 top-12"
                : "left-14 top-12",
          )}
          aria-label="Toggle Sidebar"
        >
          <div
            className={cn(
              "bg-card border border-border rounded-full p-1 transition-transform duration-200 shadow-md",
              isRTL
                ? state === "collapsed" && " rotate-180 scale-y-[-1]"
                : state === "collapsed" && " rotate-180 scale-y-[-1]",
            )}
          >
{isRTL?            <ChevronRight className="h-5 w-5 text-primary" />:
            <ChevronLeft className="h-5 w-5 text-primary" />
}          </div>
        </button>
      )}

      {/* Header  */}
      <SidebarHeader className="border-b border-white/10 bg-sidebar-accent dark:bg-sidebar-accent p-0">
        <div
          className={cn(
            "flex items-center gap-4 py-4", // Increased py further to accommodate bigger logo
            state === "collapsed"
              ? "justify-center px-2"
              : isWideLogo
                ? "justify-center px-4"
                : "justify-between px-4",
          )}
        >
          {/* Logo Container */}
          <div className={cn(
            "bg-secondary rounded-lg shrink-0 flex items-center justify-center transition-all duration-300",
            state === "collapsed" ? "p-2" : "p-1 bg-transparent" // Remove bg/padding when expanded to allow full size
          )}>
            {state === "collapsed" ? (
              // Collapsed State: Show Main Logo (scaled down safely)
              resolvedLogo ? (
                <div className="relative h-8 w-8 flex items-center justify-center">
                  <img
                    src={resolvedLogo}
                    alt="Dashboard Logo"
                    className="h-full w-full object-contain"
                  />
                </div>
              ) : (
                <Home className="h-6 w-6 text-white" />
              )
            ) : (
              // Expanded State: Show Full Logo - BIGGER
              resolvedLogo ? (
                <div className="relative flex items-center justify-center">
                  <img
                    src={resolvedLogo}
                    alt="Dashboard Logo"
                    className={cn(
                      "h-auto w-auto object-contain max-h-24 max-w-[220px]", // Increased max-height significantly
                      logoLoaded ? "relative" : "absolute invisible",
                    )}
                    onLoad={handleImageLoad}
                    onError={handleImageError}
                  />
                  {!logoLoaded && (
                    <div className="h-16 w-16 rounded bg-white/10 animate-pulse" />
                  )}
                </div>
              ) : settingsLoading ? (
                <div className="h-12 w-12 rounded bg-white/10 animate-pulse" />
              ) : (
                <Home className="h-10 w-10" />
              )
            )}
          </div>

          {state === "expanded" && !isWideLogo && (
            <div className="flex-1 flex flex-col gap-1 overflow-hidden">
              <h1 className="text-xl font-bold leading-tight text-white truncate">
                {resolvedName || t("app.title")}
              </h1>
            </div>
          )}
        </div>
      </SidebarHeader>

      {/* Content  */}
      <SidebarContent className="bg-sidebar dark:bg-sidebar gap-4 p-0">
        {/* Main Navigation */}
        <SidebarGroup className="p-0 pt-4">
          <SidebarMenu
            className={cn("gap-2", state === "collapsed" ? "px-2" : "px-4")}
          >
            {filteredMainNav.map((item) => {
              const Icon = item.icon;
              const active = isActive(item.href);

              return (
                <SidebarMenuItem key={item.href}>
                  <SidebarMenuButton
                    asChild
                    isActive={active}
                    onClick={handleNavClick}
                    tooltip={
                      state === "collapsed" ? t(item.translationKey) : undefined
                    }
                    className={cn(
                      "h-10 rounded-lg gap-2 py-2",
                      "text-sm font-semibold text-white dark:text-sidebar-foreground leading-5",
                      "transition-colors",
                      "hover:bg-white/20! dark:hover:bg-sidebar-accent! hover:text-sidebar-accent-foreground!",
                      "data-[active=true]:bg-white/20! dark:data-[active=true]:bg-sidebar-accent!",
                      state === "collapsed" ? "justify-center px-2" : "px-4",
                    )}
                  >
                    <Link
                      href={item.href}
                      className="flex items-center gap-2 w-full"
                    >
                      <Icon className="h-4 w-4 shrink-0" />
                      {state === "expanded" && (
                        <span>{t(item.translationKey)}</span>
                      )}
                    </Link>
                  </SidebarMenuButton>
                </SidebarMenuItem>
              );
            })}
          </SidebarMenu>

          {/* Separator */}
          <div className={cn("py-2", state === "collapsed" ? "px-2" : "px-4")}>
            <div className="h-px bg-white/10" />
          </div>
        </SidebarGroup>

        {/* Sections - filtered by permissions */}
        {filteredSections.map((section) => (
          <SidebarGroup key={section.translationKey} className="p-0">
            {section.collapsible ? (
              <Collapsible
                key={`collapsible-${section.translationKey}`}
                defaultOpen
                className="group/collapsible"
              >
                <div className="px-4" suppressHydrationWarning>
                  <CollapsibleTrigger
                    className="flex items-center w-full py-0 group/label"
                    suppressHydrationWarning
                  >
                    <SidebarGroupLabel
                      className={cn(
                        "text-sm text-white/60 dark:text-sidebar-foreground/60 leading-5 font-normal h-auto p-0 w-full",
                        "hover:text-white/80 dark:hover:text-sidebar-foreground/80 transition-colors",
                        "flex items-center gap-1",
                        state === "collapsed" && "sr-only",
                      )}
                    >
                      <ChevronUp className="h-4 w-4 transition-transform group-data-[state=open]/collapsible:rotate-180" />
                      <span>{t(section.translationKey)}</span>
                    </SidebarGroupLabel>
                  </CollapsibleTrigger>
                </div>
                <CollapsibleContent suppressHydrationWarning>
                  <SidebarGroupContent className="mt-2">
                    {/* Project Card for Current Project Section */}
                    {section.translationKey === "sidebar.currentProject" &&
                      state === "expanded" &&
                      projectName && (
                        <div className="px-4 mb-2">
                          <div className="bg-primary dark:bg-sidebar-primary border border-white/30 dark:border-sidebar-border rounded-lg p-2 space-y-2">
                            <h3 className="text-sm font-bold text-white dark:text-sidebar-primary-foreground leading-[1.5] truncate">
                              {displayProjectName}
                            </h3>
                            <div className="flex items-center gap-2">
                              <p
                                className="text-sm font-bold text-white dark:text-sidebar-primary-foreground shrink-0"
                                dir="ltr"
                              >
                                %{projectProgress}
                              </p>
                              <div className="flex-1 h-2 bg-white/20 dark:bg-sidebar-primary-foreground/20  overflow-hidden">
                                <div
                                  className="h-full transition-all bg-white/80 dark:bg-sidebar-primary-foreground/80"
                                  style={{
                                    width: `${projectProgress}%`
                                  }}
                                />
                              </div>
                            </div>
                          </div>
                        </div>
                      )}

                    <SidebarMenu
                      className={cn(
                        "gap-2",
                        state === "collapsed" ? "px-2" : "px-4",
                      )}
                    >
                      {section.items.map((item) => {
                        const Icon = item.icon;
                        const active = isActive(item.href);

                        return (
                          <SidebarMenuItem key={item.href}>
                            <SidebarMenuButton
                              asChild
                              isActive={active}
                              onClick={handleNavClick}
                              tooltip={
                                state === "collapsed"
                                  ? t(item.translationKey)
                                  : undefined
                              }
                              className={cn(
                                "h-10  gap-2 py-2",
                                "text-sm font-semibold text-white dark:text-sidebar-foreground leading-5",
                                "transition-colors",
                                "hover:!bg-white/20 dark:hover:!bg-sidebar-accent hover:!text-sidebar-accent-foreground",
                                "data-[active=true]:!bg-white/20 dark:data-[active=true]:!bg-sidebar-accent",
                                state === "collapsed"
                                  ? "justify-center px-2"
                                  : "px-4",
                              )}
                            >
                              <Link
                                href={item.href}
                                className="flex items-center gap-2 w-full"
                              >
                                <Icon className="h-4 w-4 shrink-0" />
                                {state === "expanded" && (
                                  <span>{t(item.translationKey)}</span>
                                )}
                              </Link>
                            </SidebarMenuButton>
                          </SidebarMenuItem>
                        );
                      })}
                    </SidebarMenu>
                  </SidebarGroupContent>
                </CollapsibleContent>
              </Collapsible>
            ) : (
              <>
                <div className="px-4">
                  <SidebarGroupLabel
                    className={cn(
                      "text-sm text-white/60 dark:text-sidebar-foreground/60 leading-5 font-normal h-auto p-0 w-full",
                      state === "collapsed" && "sr-only",
                    )}
                  >
                    {t(section.translationKey)}
                  </SidebarGroupLabel>
                </div>
                <SidebarGroupContent className="mt-2">
                  <SidebarMenu
                    className={cn(
                      "gap-2",
                      state === "collapsed" ? "px-2" : "px-4",
                    )}
                  >
                    {section.items.map((item) => {
                      const Icon = item.icon;
                      const active = isActive(item.href);

                      return (
                        <SidebarMenuItem key={item.href}>
                          <SidebarMenuButton
                            asChild
                            isActive={active}
                            onClick={handleNavClick}
                            tooltip={
                              state === "collapsed"
                                ? t(item.translationKey)
                                : undefined
                            }
                            className={cn(
                              "h-10 rounded-[4px] gap-2 py-2",
                              "text-sm font-semibold text-white dark:text-sidebar-foreground leading-5",
                              "transition-colors",
                              "hover:!bg-white/20 dark:hover:!bg-sidebar-accent hover:!text-sidebar-accent-foreground",
                              "data-[active=true]:!bg-white/20 dark:data-[active=true]:!bg-sidebar-accent",
                              state === "collapsed"
                                ? "justify-center px-2"
                                : "px-4",
                            )}
                          >
                            <Link
                              href={item.href}
                              className="flex items-center gap-2 w-full"
                            >
                              <Icon className="h-4 w-4 shrink-0" />
                              {state === "expanded" && (
                                <span>{t(item.translationKey)}</span>
                              )}
                            </Link>
                          </SidebarMenuButton>
                        </SidebarMenuItem>
                      );
                    })}
                  </SidebarMenu>
                </SidebarGroupContent>
              </>
            )}

            {/* Separator after section */}
            <div
              className={cn(
                "py-2 mt-2",
                state === "collapsed" ? "px-2" : "px-4",
              )}
            >
              <div className="h-px bg-white/10" />
            </div>
          </SidebarGroup>
        ))}
      </SidebarContent>
    </Sidebar>
  );
}
