import React, { useEffect, useMemo, useState } from "react";
import { useNavigate, useLocation } from "react-router";
import { Axiosinstance } from "../services/auth/Axiosinstance";
import { useAuthStore } from "../store/authstore";

import SidebarShell from "./sidebar/SidebarShell";
import SidebarItem from "./sidebar/SidebarItem";
import SidebarGroup from "./sidebar/SidebarGroup";

import {
  TbSmartHome,
  TbFolderOpen,
  TbFileText,
  TbFolders,
  TbFileStar,
  TbFileX,
  TbFileUpload,
  TbServer,
  TbChartDonut,
  TbFolderShare,
  TbCertificate2,
  TbChartDonut4,
  TbWallet,
  TbReceipt,
  TbMessages,
  TbMessageCirclePlus,
  TbMessageCircleUser,
  TbBell,
  TbNotification,
  TbUserCircle,
  TbFingerprint,
  TbLogout,
  TbGlobe,
  TbBrowserPlus,
} from "react-icons/tb";

/* ---------------- helpers ---------------- */
const isAnyOfPathsActive = (pathname, paths) => paths.includes(pathname);
const isPathActive = (pathname, path) => pathname === path;

/* ---------------- config ---------------- */
const GROUPS = [
  {
    key: "files",
    label: "فایل های من",
    icon: TbFolderOpen,
    paths: ["/myfile", "/myfolder", "/star", "/trash", "/upload"],
    items: [
      { label: "همه فایل ها", path: "/myfile", icon: TbFileText },
      { label: "پوشه ها", path: "/myfolder", icon: TbFolders },
      { label: "فایل‌های ستاره‌دار", path: "/star", icon: TbFileStar },
      { label: "سطل زباله", path: "/trash", icon: TbFileX },
      { label: "آپلود فایل جدید", path: "/upload", icon: TbFileUpload },
    ],
  },
  {
    key: "server",
    label: "فضای من",
    icon: TbServer,
    paths: ["/space", "/ftp", "/upgrade", "/domain"],
    items: [
      { label: "نمایش فضا", path: "/space", icon: TbChartDonut },
      { label: "مشخصات FTP من", path: "/ftp", icon: TbFolderShare },
      { label: "ارتقا پلن", path: "/upgrade", icon: TbCertificate2 },
      { label: "دامنه اختصاصی", path: "/domain", icon: TbBrowserPlus },
    ],
  },
  {
    key: "chart",
    label: "مالی",
    icon: TbChartDonut4,
    paths: ["/mywallet", "/receipt", "/discount"],
    items: [
      { label: "کیف پول من", path: "/mywallet", icon: TbWallet },
      { label: "پرداخت‌ها", path: "/receipt", icon: TbReceipt },
      // اگر صفحه discount داری و قبلاً می‌خواستی تو مالی باشه:
      // { label: "کدهای تخفیف", path: "/discount", icon: TbDiscount },
    ],
  },
  {
    key: "support",
    label: "پشتیبانی",
    icon: TbMessages,
    paths: ["/newticket", "/myticket"],
    items: [
      { label: "ارسال تیکت جدید", path: "/newticket", icon: TbMessageCirclePlus },
      { label: "مشاهده تیکت های من", path: "/myticket", icon: TbMessageCircleUser },
    ],
  },
  {
    key: "notif",
    label: "اعلان ها",
    icon: TbBell,
    paths: ["/mynotification"],
    items: [{ label: "پیام‌ها و اطلاع رسانی های سیستمی", path: "/mynotification", icon: TbNotification }],
  },
  {
    key: "account",
    label: "حساب کاربری",
    icon: TbChartDonut4,
    paths: ["/myaccount", "/twostep"],
    items: [
      { label: "پروفایل من", path: "/myaccount", icon: TbUserCircle },
      { label: "تنظیمات امنیتی (رمزعبور،ورود دومرحله‌ای)", path: "/twostep", icon: TbFingerprint },
    ],
  },
];

export default function Sidebar() {
  const [openMenu, setOpenMenu] = useState(null);
  const [isMobileOpen, setIsMobileOpen] = useState(false);

  const { refreshToken, clearTokens } = useAuthStore();
  const navigate = useNavigate();
  const location = useLocation();
  const pathname = location.pathname;

  const toggleMenu = (menuName) => {
    setOpenMenu((prev) => (prev === menuName ? null : menuName));
  };

  const logout = async () => {
    try {
      await Axiosinstance.post("accounts/logout/", { refresh: refreshToken });
    } catch (error) {
      console.error("Logout error:", error);
    } finally {
      clearTokens();
      navigate("/auth/login");
    }
  };

  // ✅ سینک کردن submenu با مسیر فعلی + بستن موبایل
  useEffect(() => {
    const found = GROUPS.find((g) => g.paths.includes(pathname));
    if (found) setOpenMenu(found.key);
    // اگر هیچ گروهی نبود، منو رو دست نمی‌زنیم تا مثل قبل رفتار کنه
    setIsMobileOpen(false);
  }, [pathname]);

  const homeActive = isPathActive(pathname, "/home") || openMenu === "home";

  return (
    <SidebarShell isMobileOpen={isMobileOpen} setIsMobileOpen={setIsMobileOpen}>
      <div
        className={`
          xl:w-2/12 md:w-4/12 sm:w-6/12 w-8/12
          dark:bg-[#001F3F] xl:dark:bg-[#16325b] xl:bg-white
          bg-[#f2f2f2]
          z-50 xl:h-fit h-full
          xl:relative fixed
          xl:rounded-4xl justify-center flex
          transform transition-transform duration-300
          overflow-auto
          ${isMobileOpen ? "translate-x-0" : "translate-x-full xl:translate-x-0"}
        `}
      >
        <ul className="w-11/12 xl:pt-0 pt-8 sm:h-full h-[85vh] sm:overflow-auto overflow-y-scroll">
          {/* داشبورد */}
          <li className="border-b dark:border-white/10 border-[#A1E3F9] p-2">
            <SidebarItem
              label="داشبورد"
              icon={TbSmartHome}
              active={homeActive}
              onClick={() => {
                toggleMenu("home");
                navigate("/home");
              }}
              iconSize="w-6 h-6"
            />
          </li>

          {/* گروه‌ها */}
          {GROUPS.map((g) => {
            const groupActive = isAnyOfPathsActive(pathname, g.paths);
            return (
              <li key={g.key} className={`border-b dark:border-white/10 border-[#A1E3F9] p-2 ${g.key === "account" ? "border-b-0" : ""}`}>
                <SidebarGroup
                  groupKey={g.key}
                  label={g.label}
                  icon={g.icon}
                  isOpen={openMenu === g.key}
                  isActiveGroup={groupActive}
                  onToggle={toggleMenu}
                  items={g.items}
                  isPathActive={(p) => isPathActive(pathname, p)}
                  navigate={navigate}
                />

                {/* فقط داخل حساب کاربری خروج رو مثل قبل نمایش بده */}
                {g.key === "account" && (openMenu === "account" || groupActive) && (
                  <ul className="w-full mt-2">
                    <li className="pr-5 py-1">
                      <button
                        onClick={logout}
                        className="dark:text-white text-right sm:text-sm text-xs px-3 py-2 flex gap-2 items-center rounded-md hover:bg-[#43BEFF40] dark:hover:bg-[#A1E3F919]"
                      >
                        <TbLogout className="w-5 h-5 text-[#43BEFF] dark:text-white" />
                        خروج از حساب
                      </button>
                    </li>
                  </ul>
                )}
              </li>
            );
          })}
        </ul>
      </div>
    </SidebarShell>
  );
}
