// File Path: web/frontend/src/components/Layout/TopNavbar.jsx
// UIX version - Theme-aware Top Navigation Bar

import React, { useState, useEffect, useRef, useCallback, useMemo } from "react";
import { Link, useLocation, useNavigate } from "react-router";
import { useAuth } from "../../services/Services";
import {
  Bars3Icon,
  XMarkIcon,
  QuestionMarkCircleIcon,
  UserCircleIcon,
  ArrowRightOnRectangleIcon,
  ChevronDownIcon,
  LockClosedIcon,
} from "@heroicons/react/24/outline";
import { Modal, Button, useUIXTheme } from "../UIX";

function TopNavbar({
  onMenuToggle,
  isMobile,
  isTablet,
  isIOS,
  isAndroid,
  isSidebarOpen,
  sidebarCollapsed,
  onCollapseToggle,
}) {
  const { authManager, meManager } = useAuth();
  const navigate = useNavigate();
  const location = useLocation();
  const { getThemeClasses } = useUIXTheme();

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

  const [currentUser, setCurrentUser] = useState(null);
  const [isLoading, setIsLoading] = useState(true);
  const [showAccountDropdown, setShowAccountDropdown] = useState(false);
  const [showLogoutWarning, setShowLogoutWarning] = useState(false);

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

  // Determine if we're on mobile/tablet for slide menu
  const shouldShowMobileMenu = isMobile || isTablet;

  // Fetch current user with proper dependencies
  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);
        }
      } catch (error) {
        if (import.meta.env.DEV) {
          console.error("[TopNavbar] Failed to fetch current user:", error);
        }
        if (isMountedRef.current) {
          setCurrentUser(null);
        }
        // Redirect to login if unauthorized
        if (error.message?.includes("not authenticated")) {
          onUnauthorized();
        }
      } finally {
        if (isMountedRef.current) {
          setIsLoading(false);
        }
      }
    };

    fetchCurrentUser();

    return () => {
      isMountedRef.current = false;
      if (dropdownMenuTimer.current) {
        clearTimeout(dropdownMenuTimer.current);
      }
    };
  }, [location.pathname, authManager, meManager, onUnauthorized]);

  // Close dropdown when clicking outside
  useEffect(() => {
    const handleClickOutside = (event) => {
      if (!event.target.closest(".account-menu-container")) {
        setShowAccountDropdown(false);
      }
    };

    if (showAccountDropdown) {
      document.addEventListener("click", handleClickOutside);
      return () => document.removeEventListener("click", handleClickOutside);
    }
  }, [showAccountDropdown]);

  // Close dropdown when navigating
  useEffect(() => {
    setShowAccountDropdown(false);
  }, [location.pathname]);

  // Paths where navbar should not be shown
  const hiddenPaths = useMemo(() => [
    "/",
    "/register",
    "/index",
    "/login",
    "/logout",
    "/verify",
    "/forgot-password",
    "/password-reset",
    "/terms",
    "/privacy",
  ], []);

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

  const handleMenuButtonClick = useCallback(() => {
    if (shouldShowMobileMenu) {
      // On mobile/tablet: toggle sidebar open/close
      onMenuToggle();
    } else {
      // On desktop: toggle sidebar collapse/expand
      onCollapseToggle();
    }
  }, [shouldShowMobileMenu, onMenuToggle, onCollapseToggle]);

  const getMenuIcon = useCallback(() => {
    // Different icons based on context
    if (shouldShowMobileMenu) {
      // Mobile/Tablet: Show X when sidebar is open, hamburger when closed
      return isSidebarOpen ? (
        <XMarkIcon className="h-6 w-6" />
      ) : (
        <Bars3Icon className="h-6 w-6" />
      );
    } else {
      // Desktop: Always show hamburger for collapse/expand
      return <Bars3Icon className="h-5 w-5" />;
    }
  }, [shouldShowMobileMenu, isSidebarOpen]);

  const getButtonTitle = useCallback(() => {
    if (shouldShowMobileMenu) {
      return isSidebarOpen ? "Close menu" : "Open menu";
    } else {
      return sidebarCollapsed ? "Expand sidebar" : "Collapse sidebar";
    }
  }, [shouldShowMobileMenu, isSidebarOpen, sidebarCollapsed]);

  const isActivePath = useCallback((path) => {
    return location.pathname.includes(path);
  }, [location.pathname]);

  const handleLogoutConfirm = useCallback(async () => {
    try {
      setShowLogoutWarning(false);
      setShowAccountDropdown(false);
      navigate("/logout");
    } catch (error) {
      if (import.meta.env.DEV) {
        console.error("[TopNavbar] Logout navigation failed:", error);
      }
      window.location.href = "/logout";
    }
  }, [navigate]);

  const handleAccountMenuEnter = useCallback(() => {
    if (!shouldShowMobileMenu) {
      clearTimeout(dropdownMenuTimer.current);
      setShowAccountDropdown(true);
    }
  }, [shouldShowMobileMenu]);

  const handleAccountMenuLeave = useCallback(() => {
    if (!shouldShowMobileMenu) {
      dropdownMenuTimer.current = setTimeout(() => {
        setShowAccountDropdown(false);
      }, 200);
    }
  }, [shouldShowMobileMenu]);

  const handleAccountMenuClick = useCallback(() => {
    if (shouldShowMobileMenu) {
      setShowAccountDropdown(!showAccountDropdown);
    }
  }, [shouldShowMobileMenu, showAccountDropdown]);

  const handleDropdownClose = useCallback(() => {
    setShowAccountDropdown(false);
  }, []);

  const handleLogoutClick = useCallback(() => {
    setShowAccountDropdown(false);
    setShowLogoutWarning(true);
  }, []);

  // Memoize user display name
  const userDisplayName = useMemo(() => {
    if (!currentUser) return "User";
    return {
      mobile: currentUser.firstName || "User",
      tablet: `Hi, ${currentUser.firstName || currentUser.email?.split("@")[0] || "User"}`,
      desktop: `Welcome, ${currentUser.firstName || currentUser.email}`,
    };
  }, [currentUser]);

  if (shouldHideNavbar || isLoading || !currentUser) {
    return null;
  }

  return (
    <>
      <nav className="fixed top-0 left-0 right-0 h-[60px] bg-gray-900 text-white flex items-center justify-between z-50 shadow-md">
        {/* Left Section */}
        <div className="flex items-center flex-1 min-w-0 px-4">
          {/* Menu Control Button - ALWAYS VISIBLE */}
          <button
            onClick={handleMenuButtonClick}
            className="p-2 rounded-md hover:bg-gray-700 transition-colors duration-200 flex items-center justify-center min-w-[44px] min-h-[44px]"
            title={getButtonTitle()}
            aria-label={getButtonTitle()}
          >
            {getMenuIcon()}
          </button>

          {/* Logo Container - Adjust position based on screen size */}
          <div
            className={`
              flex-1 flex
              ${isMobile ? "justify-center" : "justify-start ml-4"}
            `}
          >
            <Link
              to="/dashboard"
              className="flex items-center gap-2 hover:opacity-90 transition-opacity"
              aria-label="Go to Dashboard"
            >
              {/* Lock icon with theme-aware background */}
              <div className={`${getThemeClasses("bg-gradient-secondary")} p-1.5 sm:p-2 rounded-lg`}>
                <LockClosedIcon className="h-5 w-5 sm:h-6 sm:w-6 text-white" aria-hidden="true" />
              </div>
              {/* MapleFile text - hidden on mobile */}
              <span className="hidden sm:inline text-white font-semibold text-base md:text-lg tracking-tight">
                MapleFile
              </span>
            </Link>
          </div>

          {/* Spacer for mobile to balance the layout */}
          {isMobile && <div className="w-[52px]" />}
        </div>

        {/* Right Section - User Account Menu */}
        <div
          className="account-menu-container relative px-3 sm:px-5"
          onMouseEnter={handleAccountMenuEnter}
          onMouseLeave={handleAccountMenuLeave}
        >
          <button
            onClick={handleAccountMenuClick}
            className="flex items-center gap-1 text-xs sm:text-sm text-gray-300 hover:text-white hover:bg-gray-700 transition-colors duration-200 py-2 px-2 rounded-md"
          >
            <span className="sm:hidden">{userDisplayName.mobile}</span>
            <span className="hidden sm:inline md:hidden">{userDisplayName.tablet}</span>
            <span className="hidden md:inline">{userDisplayName.desktop}</span>
            <ChevronDownIcon
              className={`h-3 w-3 sm:h-4 sm:w-4 transition-transform duration-200 ${
                showAccountDropdown ? "rotate-180" : ""
              }`}
            />
          </button>

          {/* Dropdown Menu */}
          {showAccountDropdown && (
            <div
              className="absolute right-0 top-full w-48 bg-white dark:bg-gray-800 rounded-md shadow-2xl border border-gray-200 dark:border-gray-700 py-1 mt-1"
              style={{
                zIndex: 9999999,
              }}
            >
              <Link
                to="/help"
                onClick={handleDropdownClose}
                className={`
                  flex items-center px-4 py-2 text-sm transition-colors duration-200 cursor-pointer
                  ${
                    isActivePath("/help")
                      ? getThemeClasses("pagination-active")
                      : "text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700"
                  }
                `}
              >
                <QuestionMarkCircleIcon className="h-5 w-5 mr-3 flex-shrink-0" />
                <span>Help</span>
              </Link>

              <Link
                to="/me"
                onClick={handleDropdownClose}
                className={`
                  flex items-center px-4 py-2 text-sm transition-colors duration-200 cursor-pointer
                  ${
                    isActivePath("/me")
                      ? getThemeClasses("pagination-active")
                      : "text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700"
                  }
                `}
              >
                <UserCircleIcon className="h-5 w-5 mr-3 flex-shrink-0" />
                <span>My Profile</span>
              </Link>

              <hr className="my-1 border border-gray-200 dark:border-gray-700" />

              <button
                onClick={handleLogoutClick}
                className="flex items-center w-full px-4 py-2 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 cursor-pointer transition-colors duration-200"
              >
                <ArrowRightOnRectangleIcon className="h-5 w-5 mr-3 flex-shrink-0" />
                <span>Sign Off</span>
              </button>
            </div>
          )}
        </div>
      </nav>

      {/* Logout Confirmation Modal */}
      <Modal
        isOpen={showLogoutWarning}
        onClose={() => setShowLogoutWarning(false)}
        title="Are you sure?"
        footer={
          <div className="flex justify-end space-x-3">
            <Button
              variant="secondary"
              onClick={() => setShowLogoutWarning(false)}
            >
              No
            </Button>
            <Button variant="success" onClick={handleLogoutConfirm}>
              Yes
            </Button>
          </div>
        }
      >
        <p>
          You are about to log out of the system and you'll need to log in again
          next time. Are you sure you want to continue?
        </p>
      </Modal>
    </>
  );
}

export default TopNavbar;
