// File Path: web/frontend/src/components/Layout/Sidebar.jsx
// UIX version - Theme-aware Responsive Sidebar Component for MapleFile

import React, { useState, useEffect, useCallback, useMemo, useRef } from "react";
import { useLocation, useNavigate } from "react-router";
import { useAuth } from "../../services/Services";
import {
  HomeIcon,
  FolderIcon,
  CloudArrowUpIcon,
  TagIcon,
  UserCircleIcon,
  ArrowRightOnRectangleIcon,
} from "@heroicons/react/24/outline";
import { useUIXTheme } from "../UIX";

function Sidebar({
  isOpen = false,
  onClose,
  sidebarCollapsed = false,
  onCollapseToggle,
  isMobile = false,
  isTablet = false,
  isIOS = false,
  isAndroid = false,
}) {
  const { authManager, meManager } = useAuth();
  const navigate = useNavigate();
  const location = useLocation();
  const { getThemeClasses } = useUIXTheme();

  // Refs for cleanup
  const isMountedRef = useRef(true);

  const [currentUser, setCurrentUser] = useState(null);
  const [isLoading, setIsLoading] = useState(true);

  // Simple device type detection using props from Layout
  const isMobileOrTablet = useMemo(() => isMobile || isTablet, [isMobile, isTablet]);

  const onUnauthorized = useCallback(() => {
    navigate("/login?unauthorized=true");
  }, [navigate]);

  // Handle navigation and close sidebar on mobile
  const handleLinkClick = useCallback(
    (path) => {
      // Navigate first
      navigate(path);

      // Then close sidebar on mobile/tablet
      if (isMobileOrTablet && onClose) {
        // Small delay for smooth transition
        setTimeout(() => {
          onClose();
        }, 50);
      }
    },
    [navigate, isMobileOrTablet, onClose],
  );

  // Fetch current user
  useEffect(() => {
    isMountedRef.current = true;

    const fetchCurrentUser = async () => {
      if (!authManager.isAuthenticated()) {
        if (isMountedRef.current) {
          setIsLoading(false);
        }
        return;
      }

      try {
        const profile = await meManager.getCurrentUser();
        if (isMountedRef.current) {
          setCurrentUser(profile);
          setIsLoading(false);
        }
      } catch (error) {
        if (import.meta.env.DEV) {
          console.error("[Sidebar] Failed to fetch current user:", error);
        }
        if (isMountedRef.current) {
          setCurrentUser(null);
          setIsLoading(false);
        }
        // Redirect to login if unauthorized
        if (error.message?.includes("not authenticated")) {
          onUnauthorized();
        }
      }
    };

    fetchCurrentUser();

    return () => {
      isMountedRef.current = false;
    };
  }, [meManager, authManager, onUnauthorized]);

  // Lock body scroll when sidebar is open on mobile
  useEffect(() => {
    if (!isMobileOrTablet || !isOpen) return;

    // Save current scroll position
    const scrollY = window.scrollY;
    const currentPath = location.pathname;

    // Lock body scroll
    document.body.style.position = "fixed";
    document.body.style.top = `-${scrollY}px`;
    document.body.style.width = "100%";

    return () => {
      // Restore body scroll
      document.body.style.position = "";
      document.body.style.top = "";
      document.body.style.width = "";

      // Only restore scroll position if we're still on the same page
      // This prevents inappropriate scroll restoration when navigating to new pages
      if (location.pathname === currentPath) {
        window.scrollTo(0, scrollY);
      }
    };
  }, [isMobileOrTablet, isOpen, location.pathname]);

  // Paths where sidebar should not be shown
  const hiddenPaths = useMemo(() => [
    "/",
    "/register",
    "/register/recovery",
    "/register/verify-email",
    "/register/verify-success",
    "/login",
    "/login/verify-ott",
    "/login/complete",
    "/session-expired",
    "/recovery",
    "/recovery/initiate",
    "/recovery/verify",
    "/recovery/complete",
    "/terms",
    "/privacy",
  ], []);

  const shouldHideSidebar = useMemo(() =>
    hiddenPaths.some(
      (path) =>
        location.pathname === path ||
        (path !== "/" && location.pathname.startsWith(path)),
    ),
    [hiddenPaths, location.pathname]
  );

  const isActivePath = useCallback((path) => {
    // Exact match
    if (location.pathname === path) {
      return true;
    }

    // For /me (Profile), only match exactly - don't match /me/tags/* or other /me/* paths
    if (path === "/me") {
      return false;
    }

    // For /file-manager, only highlight if we're on a sub-path that's not in the menu
    if (path === "/file-manager") {
      const subPaths = ["/file-manager/upload"];
      const isOnSubPath = subPaths.some(subPath => location.pathname.startsWith(subPath));

      // Only highlight File Manager if we're on /file-manager/* but NOT on a specific sub-menu item
      return location.pathname.startsWith("/file-manager/") && !isOnSubPath;
    }

    // For other paths, use startsWith for sub-pages
    return location.pathname.startsWith(path + "/");
  }, [location.pathname]);

  // MapleFile menu structure
  const menuSections = useMemo(() => [
    {
      label: "Main",
      items: [
        { path: "/dashboard", label: "Dashboard", icon: HomeIcon },
        { path: "/file-manager", label: "File Manager", icon: FolderIcon },
        { path: "/file-manager/upload", label: "Upload Files", icon: CloudArrowUpIcon },
        { path: "/me/tags/search", label: "Search by Tags", icon: TagIcon },
      ],
    },
    {
      label: "Account",
      items: [
        { path: "/me", label: "Profile", icon: UserCircleIcon },
        { path: "/logout", label: "Logout", icon: ArrowRightOnRectangleIcon },
      ],
    },
  ], []);

  // Determine sidebar width
  const getSidebarWidth = useCallback(() => {
    if (isMobile) return "w-72";
    if (isTablet) return sidebarCollapsed ? "w-16" : "w-56";
    return sidebarCollapsed ? "w-16" : "w-64"; // Desktop
  }, [isMobile, isTablet, sidebarCollapsed]);

  // Determine if labels should show
  const shouldShowLabels = useMemo(() => !sidebarCollapsed || isMobileOrTablet, [sidebarCollapsed, isMobileOrTablet]);

  // Don't render if sidebar should be hidden
  if (shouldHideSidebar || isLoading || !currentUser) {
    return null;
  }

  return (
    <>
      {/* Overlay for mobile/tablet - Only show when sidebar is open */}
      {isMobileOrTablet && isOpen && (
        <div
          className="fixed inset-0 bg-black bg-opacity-50 z-[999]"
          style={{ top: "60px" }}
          onClick={onClose}
        />
      )}

      {/* Sidebar Container */}
      <div
        className={`
          fixed left-0 top-[60px] h-[calc(100vh-60px)]
          bg-gray-900 text-gray-200
          ${getSidebarWidth()}
          transition-transform duration-300 ease-in-out
          overflow-y-auto overflow-x-hidden
          z-[1000]
          ${
            // This is the key: On mobile/tablet, control visibility with transform
            isMobileOrTablet
              ? isOpen
                ? "transform translate-x-0"
                : "transform -translate-x-full"
              : "transform translate-x-0" // Always visible on desktop
          }
        `}
      >
        {/* Sidebar Content */}
        <div className={isMobile ? "px-4 py-4" : "px-3 py-3"}>
          {/* Menu Sections */}
          {menuSections.map((section, sectionIndex) => (
            <div
              key={sectionIndex}
              className={sectionIndex < menuSections.length - 1 ? "mb-6" : ""}
            >
              {/* Section Label */}
              {shouldShowLabels && (
                <div className="text-xs font-semibold text-gray-400 uppercase tracking-wider mb-2 px-3">
                  {section.label}
                </div>
              )}

              {/* Menu Items */}
              <ul className="space-y-1">
                {section.items.map((item, itemIndex) => {
                  const Icon = item.icon;
                  const isActive = isActivePath(item.path);

                  return (
                    <li key={itemIndex}>
                      <button
                        onClick={() => handleLinkClick(item.path)}
                        className={`
                          w-full
                          relative flex items-center
                          ${shouldShowLabels ? "justify-start" : "justify-center"}
                          ${isMobile ? "px-4 py-3" : sidebarCollapsed && !isTablet ? "px-2 py-2" : "px-3 py-2"}
                          rounded-md
                          ${isMobile ? "text-base" : "text-sm"}
                          transition-all duration-200
                          cursor-pointer
                          ${
                            isActive
                              ? getThemeClasses("pagination-active")
                              : "text-gray-300 hover:bg-gray-700"
                          }
                        `}
                        title={!shouldShowLabels ? item.label : undefined}
                      >
                        <div
                          className={`flex items-center ${shouldShowLabels ? "" : "justify-center w-full"}`}
                        >
                          <Icon
                            className={`
                              ${isMobile ? "h-6 w-6" : "h-5 w-5"}
                              ${shouldShowLabels ? "mr-3" : ""}
                              flex-shrink-0
                            `}
                          />
                          {shouldShowLabels && (
                            <span className="text-left">{item.label}</span>
                          )}
                        </div>
                      </button>
                    </li>
                  );
                })}
              </ul>
            </div>
          ))}
        </div>
      </div>
    </>
  );
}

export default Sidebar;
