"use client";
import Image from "next/image";
import SiteLogo from "@/public/images/site-logo.webp";
import SiteLogoIcon from "@/public/images/site-logo-icon.webp";
import Link from "next/link";
import { ROUTES } from "@/utils/Routing";
import { usePathname, useRouter } from "next/navigation";
import { useAuthStore } from "@/zustand/auth/useAuthStore";
import ThemeToggle from "@/utils/ThemeToggle";
import { getCookie, setCookie } from "cookies-next";
import { useEffect, useState } from "react";
import { getClientDictionary } from "@/utils/getClientDictionary";
import { DashboardContent } from "@/types/staticContent/dashboard.content.type";

type Props = {
  toggleSidebar: boolean;
  setToggleSidebar: (value: boolean) => void;
};

interface MenuItem {
  menuTitle: string;
  menuUrl: string;
  menuIconName: string;
  subMenuLists?: SubMenuItem[];
}

interface SubMenuItem {
  menuTitle: string;
  menuUrl: string;
  menuIconName: string;
}

const Sidebar = ({ toggleSidebar, setToggleSidebar }: Props) => {
  const [locale, setLocale] = useState<string>("en");
  const [isMobile, setIsMobile] = useState(false);
  const [openMenus, setOpenMenus] = useState<Set<string>>(new Set());
  const pathname = usePathname();
  const router = useRouter();
  const staticContent = getClientDictionary(locale, "dashboard") as DashboardContent;

  const SidebarMenuLists: MenuItem[] = [
    {
      menuTitle: staticContent.SIDEBAR.DASHBOARD,
      menuUrl: ROUTES.DASHBOARD,
      menuIconName: "icon-dashboard",
    },
    {
      menuTitle: staticContent.SIDEBAR.DOCUMENTS,
      menuUrl: ROUTES.DOCUMENTS,
      menuIconName: "icon-documents",
    },
    {
      menuTitle: staticContent.SIDEBAR.AI_ASSISTANT,
      menuUrl: ROUTES.AI_ASSISTANT,
      menuIconName: "icon-ai-assistant",
    },
    {
      menuTitle: staticContent.SIDEBAR.POLICY_COMPLIANCE_REVIEW,
      menuUrl: ROUTES.POLICY_COMPLIANCE_REVIEW,
      menuIconName: "icon-control-suggestion",
    },
    {
      menuTitle: "Audit Management",
      menuUrl: ROUTES.AUDIT_MANAGEMENT,
      menuIconName: "icon-audit-shield",
      subMenuLists: [
        {
          menuTitle: "Audit Dashboard",
          menuUrl: ROUTES.AUDIT_DASHBOARD,
          menuIconName: "icon-dashboard",
        },
        {
          menuTitle: "Assessment",
          menuUrl: ROUTES.AUDIT_ASSESSMENT,
          menuIconName: "icon-document-check",
        },
        {
          menuTitle: "Audit Plan",
          menuUrl: ROUTES.AUDIT_PLAN,
          menuIconName: "icon-calendar",
        },
        {
          menuTitle: "Projects",
          menuUrl: ROUTES.AUDIT_PROJECTS,
          menuIconName: "icon-projects",
        },
        {
          menuTitle: "Issue Tracking",
          menuUrl: ROUTES.ISSUE_TRACKING,
          menuIconName: "icon-caution",
        },
        {
          menuTitle: "Audit Reports",
          menuUrl: ROUTES.AUDIT_REPORTS,
          menuIconName: "icon-report",
        },
        {
          menuTitle: "Response Tracking",
          menuUrl: ROUTES.RESPONSE_TRACKING,
          menuIconName: "icon-chat",
        },
      ],
    },
    {
      menuTitle: staticContent.SIDEBAR.SETTINGS,
      menuUrl: ROUTES.SETTINGS,
      menuIconName: "icon-settings",
    },
  ];

  useEffect(() => {
    const lang = (getCookie("language") as string) || "en";
    setLocale(lang);
  }, []);

  useEffect(() => {
    if (toggleSidebar && isMobile) {
      document.body.classList.add("overflow-hidden");
    } else {
      document.body.classList.remove("overflow-hidden");
    }
  }, [toggleSidebar, isMobile]);

  useEffect(() => {
    const handleResize = () => {
      setIsMobile(window.innerWidth < 1199);
    };
    handleResize();
    window.addEventListener("resize", handleResize);
    return () => window.removeEventListener("resize", handleResize);
  }, []);

  const handleLanguage = () => {
    const html = document.documentElement;
    const newLang = locale === "en" ? "ar" : "en";

    setLocale(newLang);

    if (newLang === "ar") {
      html.classList.add("rtl");
      html.setAttribute("dir", "rtl");
      html.setAttribute("lang", "ar");
    } else {
      html.classList.remove("rtl");
      html.setAttribute("dir", "ltr");
      html.setAttribute("lang", "en");
    }

    setCookie("language", newLang, {
      path: "/",
      maxAge: 60 * 60 * 24 * 365,
    });
    router.refresh();
  };

  const toggleSubmenu = (title: string) => {
    setOpenMenus((prev) => {
      const newSet = new Set(prev);
      if (newSet.has(title)) {
        newSet.delete(title);
      } else {
        newSet.add(title);
      }
      return newSet;
    });
  };

  const isActive = (url: string) => pathname === url;
  const activeClasses = "bg-secondary27 text-primary-c1";

  return (
    <aside
      className={`w-full bg-secondary11 border-grey2b h-dvh fixed top-0 duration-300 ease-in-out overflow-auto z-20 scrollbar-0 scroll-smooth shadow-[0_10px_30px_rgba(0,0,0,0.6)] xl:shadow-none ${locale === "en"
        ? `${toggleSidebar ? "left-0" : "-left-full"} xl:left-0 border-r`
        : `${toggleSidebar ? "right-0" : "-right-full"} xl:right-0 border-l`
        } ${toggleSidebar
          ? "max-w-[300px] xl:max-w-[100px] xl:max-w-[120px]"
          : "max-w-[300px] xl:max-w-[310px] 2xl:max-w-[360px]"
        }`}
    >
      {/* Header / Logo + Toggle */}
      <div className="flex bg-secondary11 items-center justify-between mx-2 pt-3 pb-3 2xl:pt-6 2xl:pb-5 2xl:mx-2.5 border-b border-grey2b sticky top-0 z-[2]">
        <div className="max-w-[169px] flex justify-center items-center h-16 overflow-hidden">
          <Link href={ROUTES.DASHBOARD}>
            <Image
              src={SiteLogoIcon}
              width={110}
              height={110}
              alt="Site Logo Icon"
              className={`duration-300 hidden xl:block w-15 h-15 shrink-0 ease-in-out ${toggleSidebar ? "" : "opacity-0 w-0! h-0!"
                }`}
            />
          </Link>
          <Link href={ROUTES.DASHBOARD}>
            <Image
              src={SiteLogo}
              width={169}
              height={63}
              alt="Site Logo"
              className={`duration-300 ease-in-out ${toggleSidebar ? "xl:opacity-0 xl:w-0" : ""}`}
            />
          </Link>
        </div>
        <button
          onClick={() => setToggleSidebar(!toggleSidebar)}
          className={`icon hover:bg-primary icon-chevron-left bg-grey66 w-5 h-5 2xl:w-6 2xl:h-6 cursor-pointer shrink-0 duration-300 ease-in-out ${locale === "en"
            ? `${toggleSidebar ? "rotate-0 xl:rotate-180" : "rotate-0"}`
            : `${toggleSidebar ? "rotate-180 xl:rotate-0" : "rotate-180"}`
            }`}
        />
      </div>

      {/* Menu Items */}
      <ul className="py-4 px-2.5 flex flex-col gap-y-2 2xl:gap-y-2.5">
        {SidebarMenuLists.map((item) => {
          const hasSubmenu = !!item.subMenuLists?.length;
          const isOpen = openMenus.has(item.menuTitle);
          const isAnyChildActive = item.subMenuLists?.some((sub) => isActive(sub.menuUrl));

          return (
            <li key={item.menuTitle} className="block">
              {hasSubmenu ? (
                // Parent with submenu → toggle on click
                <button
                  type="button"
                  onClick={() => toggleSubmenu(item.menuTitle)}
                  className={`relative flex w-full items-center gap-2 xl:gap-2.5 text-grey-de 2xl:gap-3.5 duration-300 ease-in-out font-medium leading-tight px-3.5 xl:px-5 py-3 xl:py-3.5 rounded-l-xl md:rounded-l-2xl 2xl:rounded-l-[20px] group hover:bg-secondary27 hover:text-primary-c1 ${toggleSidebar ? "text-sm md:text-base xl:text-[0px]" : "text-sm md:text-base 2xl:text-xl"
                    } ${(isActive(item.menuUrl) || isAnyChildActive) ? activeClasses : ""}`}
                >
                  <i
                    className={`icon ${item.menuIconName} ${isActive(item.menuUrl) || isAnyChildActive ? "bg-primary" : "bg-grey-de"
                      } w-5 h-5 md:h-6 md:w-6 2xl:w-8.5 2xl:h-8.5 group-hover:bg-primary-c1 shrink-0`}
                  />
                  <span className={`flex-1  ${locale === "en" ? "text-left" : "text-right"}`}>{item.menuTitle}</span>
                  <i
                    className={`icon icon-chevron-left w-5 h-5 bg-grey-de duration-200 ease-in-out ${isOpen ? "-rotate-90" : "rotate-270"
                      } ${locale === "en" ? "right-4" : "left-4"}`}
                  />
                </button>
              ) : (
                // Simple link – no submenu
                <Link
                  href={item.menuUrl}
                  className={`relative flex items-center gap-2 xl:gap-2.5 text-grey-de 2xl:gap-3.5 duration-300 ease-in-out font-medium leading-tight px-3.5 xl:px-5 py-3 xl:py-3.5 rounded-l-xl md:rounded-l-2xl 2xl:rounded-l-[20px] group hover:bg-secondary27 hover:text-primary-c1 ${toggleSidebar ? "text-sm md:text-base xl:text-[0px]" : "text-sm md:text-base 2xl:text-xl"
                    } ${isActive(item.menuUrl) ? activeClasses : ""}`}
                  onClick={() => isMobile && setToggleSidebar(false)}
                >
                  <i
                    className={`icon ${item.menuIconName} ${isActive(item.menuUrl) ? "bg-primary" : "bg-grey-de"
                      } w-5 h-5 md:h-6 md:w-6 2xl:w-8.5 2xl:h-8.5 group-hover:bg-primary-c1 shrink-0`}
                  />
                  {item.menuTitle}
                </Link>
              )}

              {/* Submenu – only shown when parent has submenu & is open */}
              {hasSubmenu && isOpen && (
                <ul className="pl-9 mt-1 flex flex-col gap-y-1">
                  {item.subMenuLists!.map((sub) => (
                    <li key={sub.menuTitle} className="block">
                      <Link
                        href={sub?.menuUrl}
                        className={`flex items-center gap-2 xl:gap-2.5 text-grey-de 2xl:gap-3.5 duration-300 ease-in-out font-medium leading-tight px-3.5 xl:px-5 py-3 xl:py-3.5 rounded-l-xl md:rounded-l-2xl 2xl:rounded-l-[20px] group hover:bg-secondary27 hover:text-primary-c1 ${toggleSidebar
                          ? "text-sm md:text-base xl:text-[0px]"
                          : "text-sm md:text-base 2xl:text-xl"
                          } ${pathname === sub.menuUrl ? activeClasses : ""}`}
                        onClick={(e) => isMobile && (
                          e.stopPropagation(),
                          setToggleSidebar(false)
                        )}
                      >
                        <i
                          className={`icon ${sub?.menuIconName} ${pathname === sub.menuUrl ? "bg-primary" : "bg-grey-de"
                            } w-5 h-5 md:h-6 md:w-6 2xl:w-8.5 2xl:h-8.5  group-hover:bg-primary-c1 shrink-0`}
                        ></i>
                        {sub?.menuTitle}
                      </Link>
                    </li>
                  ))}
                </ul>
              )}
            </li>
          );
        })}
      </ul>

      {/* Bottom section – theme & language */}
      <div className="bg-secondary11 p-3 sticky bottom-0 z-[2] flex items-center flex-wrap justify-between gap-2">
        <ThemeToggle />
        <button
          type="button"
          className="inline-flex items-center gap-2 rounded-md border border-grey2b bg-secondary px-3 py-1.5 text-sm font-medium text-light hover:bg-primary hover:text-white duration-300 ease-in-out cursor-pointer"
          onClick={handleLanguage}
        >
          {locale === "en" ? "AR" : "EN"}
        </button>
      </div>
    </aside>
  );
};

export default Sidebar;