import { NavLink, Route, Routes, useLocation } from "react-router-dom";
import {
  Menu,
  X,
  MessageSquare,
  Newspaper,
  Goal,
  Eye,
  Camera as Instagram,
  Palette,
  Contact,
  Link,
  ChevronLeft,
  ChevronRight,
  LayoutGrid,
  Settings,
  ShieldAlert,
  Home,
} from "lucide-react";
import { useAuth } from "@/shared/context/AuthContext";
import { Messages } from "@/user-management/web-Management/LeadershipMessage/Messages";
import { Goals } from "@/user-management/web-Management/Goals/Goals";
import { Vision } from "@/user-management/web-Management/Vision/Vision";
import { SocialMedia } from "@/user-management/web-Management/SocialMedia/SocialMedia";
import { AddGoal } from "@/user-management/web-Management/Goals/AddGoal";
import { AddVision } from "@/user-management/web-Management/Vision/AddVision";
import { News } from "@/user-management/web-Management/News/News";
import { ContactUs } from "@/user-management/web-Management/ContactUs/ContactUs";
import { Modules } from "@/user-management/web-Management/Modules/Modules";
import { NewsCategory } from "@/user-management/web-Management/NewsCategory/NewsCategory";
import { AddNewsCategory } from "./NewsCategory/AddNewsCategory";
import { EditNewsCategory } from "./NewsCategory/EditNewsCategory";
import { AddNews } from "./News/AddNews";
import { EditNews } from "./News/EditNews";
import { useTranslation } from "react-i18next";
import { useState, useEffect, useMemo } from "react";
import { AddMessage } from "./LeadershipMessage/AddMessage";
import { EditMessage } from "./LeadershipMessage/EditMessage";
import { ViewMessage } from "./LeadershipMessage/ViewMessage";
import { ViewGoal } from "./Goals/ViewGoal";
import { EditGoal } from "./Goals/EditGoal";
import { ViewVision } from "./Vision/ViewVision";
import { EditVision } from "./Vision/EditVision";
import { EditSocialMedia } from "./SocialMedia/EditSocialMedia";
import { AddSocialMedia } from "./SocialMedia/AddSocialMedia";
import { EditTheme } from "./Theme/EditTheme";
import { AddContactUs } from "./ContactUs/AddContactUs";
import { EditContactUs } from "./ContactUs/EditContactUs";
import { AddModules } from "./Modules/AddModules";
import { EditModules } from "./Modules/EditModules";
import { TemplateConfigurationPage } from "./TemplateConfiguration/TemplateConfigurationPage";
import { TemplateSettingValuePage } from "./TemplateSettingValues/TemplateSettingValuePage";
// import { Branding } from "./Branding/Branding";
import { cn } from "@/shared/lib/utils";

interface MenuItem {
  label: string;
  href?: string;
  icon: React.ReactNode;
}

interface MenuSection {
  title: string;
  items: MenuItem[];
}

export const WebManagementHomePage = () => {
  const { user } = useAuth();
  const { t } = useTranslation();
  const location = useLocation();
  const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);
  const [isSidebarCollapsed, setIsSidebarCollapsed] = useState(false);

  const menuSections: MenuSection[] = [
    {
      title: "menu.content",
      items: [
        {
          label: "officeHead.title",
          href: "/user-management/web-management/LeadershipMessage/LeadershipMessage",
          icon: <MessageSquare className="h-4 w-4" />,
        },
        {
          label: "Goals",
          href: "/user-management/web-management/Goals/goals",
          icon: <Goal className="h-4 w-4" />,
        },
        {
          label: "Vision",
          href: "/user-management/web-management/Vision/vision",
          icon: <Eye className="h-4 w-4" />,
        },
        {
          label: "nav.news",
          href: "/user-management/web-management/News/news",
          icon: <Newspaper className="h-4 w-4" />,
        },
        {
          label: "newsCategory",
          href: "/user-management/web-management/Category/Category",
          icon: <LayoutGrid className="h-4 w-4" />,
        },
      ],
    },
    {
      title: "menu.settingsAndConfig",
      items: [
        {
          label: "modules",
          href: "/user-management/web-management/Modules/Modules",
          icon: <Link className="h-4 w-4" />,
        },
        {
          label: "socialMedia",
          href: "/user-management/web-management/SocialMedia/SocialMedia",
          icon: <Instagram className="h-4 w-4" />,
        },
        {
          label: "contactUs",
          href: "/user-management/web-management/ContactUs/ContactUs",
          icon: <Contact className="h-4 w-4" />,
        },
      ],
    },
    {
      title: "menu.themesAndBranding",
      items: [
        // {
        //   label: "branding.title",
        //   href: "/user-management/web-management/Branding/Branding",
        //   icon: <ShieldAlert className="h-4 w-4" />,
        // },
        {
          label: "theme",
          href: "/user-management/web-management/Theme/Theme",
          icon: <Palette className="h-4 w-4" />,
        },
      ],
    },
    {
      title: "menu.templates",
      items: [
        {
          label: "template.title",
          href: "/user-management/web-management/TemplateConfiguration/templates",
          icon: <Settings className="h-4 w-4" />,
        },
        {
          label: "templateSettingValue.title",
          href: "/user-management/web-management/TemplateSettingValues/values",
          icon: <Settings className="h-4 w-4" />,
        },
      ],
    },
  ];

  // Flattened list for matching logic
  const allMenuItems = useMemo(() => {
    return menuSections.flatMap((sec) => sec.items);
  }, []);

  // Close mobile menu when route changes
  useEffect(() => {
    setIsMobileMenuOpen(false);
  }, [location.pathname]);

  // Close mobile menu on resize
  useEffect(() => {
    const handleResize = () => {
      if (window.innerWidth >= 768) {
        setIsMobileMenuOpen(false);
      }
    };
    window.addEventListener("resize", handleResize);
    return () => window.removeEventListener("resize", handleResize);
  }, []);

  const isMenuHrefActive = (href?: string, pathname?: string) => {
    if (!href || !pathname) return false;
    const hrefN = href.toLowerCase();
    const pathN = pathname.toLowerCase();

    if (pathN === hrefN) return true;

    const baseSegment = hrefN.split("/").slice(0, -1).join("/");
    if (pathN.startsWith(baseSegment)) {
      const lastPart = hrefN.split("/").pop();
      if (lastPart && pathN.includes(lastPart)) {
        return true;
      }
    }
    return false;
  };

  // Find current active menu item
  const activeMenuItem = useMemo(() => {
    return (
      allMenuItems
        .filter((mi) => isMenuHrefActive(mi.href, location.pathname))
        .sort((a, b) => (b.href?.length || 0) - (a.href?.length || 0))[0] ||
      null
    );
  }, [allMenuItems, location.pathname]);

  return (
    <div className="flex w-full min-h-screen mt-5 bg-slate-50 dark:bg-slate-900 transition-colors duration-300">
      {/* Mobile Sidebar Drawer Overlay */}
      {isMobileMenuOpen && (
        <div
          className="fixed inset-0 bg-slate-950/40 backdrop-blur-sm md:hidden"
          onClick={() => setIsMobileMenuOpen(false)}
        />
      )}

      {/* Sidebar Navigation */}
      <aside
        className={cn(
          "bg-white dark:bg-slate-950 border-r border-slate-200/80 dark:border-slate-800/80 transition-all duration-300 ease-in-out flex flex-col",
          isMobileMenuOpen
            ? "fixed left-0 top-0 h-full w-72 md:w-80 shadow-2xl z-40"
            : "hidden md:flex sticky top-0 h-screen",
          isSidebarCollapsed ? "w-20" : "w-72 lg:w-80",
        )}
      >
        {/* Sidebar Brand Header */}
        <div className="h-16 flex items-center justify-between px-6 border-b border-slate-100 dark:border-slate-900">
          {!isSidebarCollapsed && (
            <div className="flex items-center gap-2">
              <div className="h-8 w-8 rounded-xl bg-gradient-to-tr from-violet-600 to-purple-600 flex items-center justify-center text-white shadow-md shadow-violet-500/10">
                <Settings className="h-4 w-4" />
              </div>
              <span className="text-sm font-semibold tracking-wide bg-gradient-to-r from-slate-900 to-slate-700 dark:from-white dark:to-slate-300 bg-clip-text text-transparent">
                {t("organization.webManagement") || "Web Management"}
              </span>
            </div>
          )}

          {isSidebarCollapsed && (
            <div className="mx-auto h-8 w-8 rounded-xl bg-gradient-to-tr from-violet-600 to-purple-600 flex items-center justify-center text-white shadow-md shadow-violet-500/10">
              <Settings className="h-4 w-4" />
            </div>
          )}

          {!isSidebarCollapsed && (
            <button
              onClick={() => setIsSidebarCollapsed(true)}
              className="hidden md:flex p-1.5 rounded-lg border border-slate-100 dark:border-slate-800 text-slate-500 dark:text-slate-400 hover:bg-slate-50 dark:hover:bg-slate-900 transition-all"
              title="Collapse menu"
            >
              <ChevronLeft className="h-4 w-4" />
            </button>
          )}

          {isMobileMenuOpen && (
            <button
              onClick={() => setIsMobileMenuOpen(false)}
              className="md:hidden p-1.5 rounded-lg border border-slate-100 dark:border-slate-800 text-slate-500 dark:text-slate-400 hover:bg-slate-50 dark:hover:bg-slate-900 transition-all"
            >
              <X className="h-4 w-4" />
            </button>
          )}
        </div>

        {/* Sidebar Nav Items */}
        <nav className="flex-1 px-4 py-6 overflow-y-auto overflow-x-hidden space-y-6">
          {menuSections.map((section, secIdx) => (
            <div key={secIdx} className="space-y-2">
              {!isSidebarCollapsed && (
                <h3 className="px-3 text-xxs font-bold uppercase tracking-wider text-slate-400 dark:text-slate-500">
                  {t(section.title)}
                </h3>
              )}

              <div className="space-y-1">
                {section.items.map((item) => {
                  const isActive = isMenuHrefActive(
                    item.href,
                    location.pathname,
                  );
                  return (
                    <NavLink
                      key={item.label}
                      to={item.href || "#"}
                      className={cn(
                        "flex items-center gap-3 px-3 py-2.5 rounded-xl text-sm font-medium transition-all duration-200 relative group",
                        isActive
                          ? "bg-violet-50 dark:bg-violet-950/40 text-violet-600 dark:text-violet-400 font-semibold shadow-sm border border-violet-100/50 dark:border-violet-950/20"
                          : "text-slate-600 dark:text-slate-400 hover:bg-slate-50 dark:hover:bg-slate-900/60 hover:text-slate-900 dark:hover:text-slate-200",
                        isSidebarCollapsed ? "justify-center" : "",
                      )}
                    >
                      {/* Active indicator line */}
                      {isActive && !isSidebarCollapsed && (
                        <div className="absolute left-0 w-1 h-5 rounded-r-full bg-violet-600 dark:bg-violet-400" />
                      )}

                      <span
                        className={cn(
                          "transition-transform group-hover:scale-105 duration-200",
                          isActive
                            ? "text-violet-600 dark:text-violet-400"
                            : "text-slate-400 dark:text-slate-500 group-hover:text-slate-500 dark:group-hover:text-slate-400",
                        )}
                      >
                        {item.icon}
                      </span>

                      {!isSidebarCollapsed && (
                        <span className="truncate flex-1">{t(item.label)}</span>
                      )}

                      {/* Tooltip for collapsed state */}
                      {isSidebarCollapsed && (
                        <div className="absolute left-16 bg-slate-900 dark:bg-slate-800 text-white text-xs rounded px-2 py-1 opacity-0 pointer-events-none group-hover:opacity-100 transition-opacity whitespace-nowrap z-50 shadow-md">
                          {t(item.label)}
                        </div>
                      )}
                    </NavLink>
                  );
                })}
              </div>
            </div>
          ))}
        </nav>

        {/* Collapsed Sidebar Expand Toggle */}
        {isSidebarCollapsed && (
          <div className="p-4 border-t border-slate-100 dark:border-slate-900 flex justify-center">
            <button
              onClick={() => setIsSidebarCollapsed(false)}
              className="p-1.5 rounded-lg border border-slate-100 dark:border-slate-800 text-slate-500 dark:text-slate-400 hover:bg-slate-50 dark:hover:bg-slate-900 transition-all"
              title="Expand menu"
            >
              <ChevronRight className="h-4 w-4" />
            </button>
          </div>
        )}
      </aside>

      {/* Main Panel Content */}
      <main className="flex-1 flex flex-col min-w-0">
        {/* Mobile Header Bar */}
        <header className="md:hidden h-16 flex items-center justify-between px-6 bg-white dark:bg-slate-950 border-b border-slate-200/80 dark:border-slate-800/80 sticky top-0 z-30">
          <button
            onClick={() => setIsMobileMenuOpen(true)}
            className="p-2 rounded-xl hover:bg-slate-50 dark:hover:bg-slate-900 transition-all border border-slate-100 dark:border-slate-850"
          >
            <Menu className="h-5 w-5 text-slate-700 dark:text-slate-300" />
          </button>

          <h1 className="text-base font-semibold text-slate-900 dark:text-white">
            {activeMenuItem ? t(activeMenuItem.label) : t("webManagement")}
          </h1>
          <div className="w-9" />
        </header>

        {/* Desktop Header bar / Breadcrumbs */}
        <header className="hidden md:flex h-16 items-center px-8 bg-white/70 dark:bg-slate-950/70 backdrop-blur border-b border-slate-200/40 dark:border-slate-800/40 sticky top-0">
          <div className="flex items-center gap-2 text-sm text-slate-500 dark:text-slate-400">
            <Home className="h-4 w-4 text-slate-400" />
            <ChevronRight className="h-3 w-3 text-slate-300" />
            <span className="text-slate-400">{t("portal.settings")}</span>
            {activeMenuItem && (
              <>
                <ChevronRight className="h-3 w-3 text-slate-300" />
                <span className="text-slate-900 dark:text-white font-semibold">
                  {t(activeMenuItem.label)}
                </span>
              </>
            )}
          </div>
        </header>

        {/* Inner Page Router Component view */}
        <div className="flex-1 overflow-y-auto overflow-x-hidden">
          <Routes>
            {/* Leadership Message */}
            <Route
              path="/LeadershipMessage/LeadershipMessage"
              element={<Messages />}
            />
            <Route
              path="/LeadershipMessage/AddLeadershipMessage"
              element={<AddMessage />}
            />
            <Route
              path="/LeadershipMessage/EditLeadershipMessage/:id"
              element={<EditMessage />}
            />
            <Route
              path="/LeadershipMessage/ViewLeadershipMessage/:id"
              element={<ViewMessage />}
            />

            {/* Goals */}
            <Route path="/Goals/goals" element={<Goals />} />
            <Route path="/Goals/AddGoal" element={<AddGoal />} />
            <Route path="/Goals/EditGoal/:id" element={<EditGoal />} />
            <Route path="/Goals/ViewGoal/:id" element={<ViewGoal />} />

            {/* Vision */}
            <Route path="/Vision/vision" element={<Vision />} />
            <Route path="/Vision/AddVision" element={<AddVision />} />
            <Route path="/Vision/ViewVision/:id" element={<ViewVision />} />
            <Route path="/Vision/EditVision/:id" element={<EditVision />} />

            {/* News */}
            <Route path="/News/news" element={<News />} />
            <Route path="/News/AddNews" element={<AddNews />} />
            <Route path="/News/EditNews/:id" element={<EditNews />} />

            {/* News Category */}
            <Route path="/Category/Category" element={<NewsCategory />} />
            <Route path="/Category/AddCategory" element={<AddNewsCategory />} />
            <Route
              path="/Category/EditCategory/:id"
              element={<EditNewsCategory />}
            />

            {/* Social Media */}
            <Route path="/SocialMedia/SocialMedia" element={<SocialMedia />} />
            <Route
              path="/SocialMedia/AddSocialMedia"
              element={<AddSocialMedia />}
            />
            <Route
              path="/SocialMedia/EditSocialMedia/:id"
              element={<EditSocialMedia />}
            />

            {/* Theme */}
            <Route path="/Theme/Theme" element={<EditTheme />} />
            {/* Branding */}
            {/* <Route path="/Branding/Branding" element={<Branding />} /> */}

            {/* Contact Us */}
            <Route path="/ContactUs/ContactUs" element={<ContactUs />} />
            <Route path="/ContactUs/AddContactUs" element={<AddContactUs />} />
            <Route
              path="/ContactUs/EditContactUs/:id"
              element={<EditContactUs />}
            />

            {/* Modules */}
            <Route path="/Modules/Modules" element={<Modules />} />
            <Route path="/Modules/AddModules" element={<AddModules />} />
            <Route path="/Modules/EditModules/:id" element={<EditModules />} />

            {/* Template Configuration */}
            <Route
              path="/TemplateConfiguration/*"
              element={<TemplateConfigurationPage />}
            />

            {/* Template Setting Values */}
            <Route
              path="/TemplateSettingValues/*"
              element={<TemplateSettingValuePage />}
            />
          </Routes>
        </div>
      </main>
    </div>
  );
};
