import React, { useRef } from 'react';
import { createPortal } from 'react-dom';
import { Link } from 'react-router-dom';
import { Menu, X } from 'lucide-react';
import { useTheme } from '../contexts/ThemeContext';
import { getThemeTextClasses } from '../utils/themeUtils';

interface NavbarProps {
  isMobileMenuOpen: boolean;
  onMobileMenuToggle: () => void;
  onLinkClick?: () => void;
  renderMobileLinksOnly?: boolean;
  mobileMenuContent?: React.ReactNode;
}

// eslint-disable-next-line react-refresh/only-export-components
export const navLinks = [
  { to: '/', label: 'Home' },
  { to: '/rooms', label: 'Rooms' },
  { to: '/services', label: 'Services' },
  { to: '/about', label: 'About' },
  { to: '/contact', label: 'Contact' },
  { to: '/blog', label: 'Blog' },
];

const Navbar: React.FC<NavbarProps> = ({ 
  isMobileMenuOpen, 
  onMobileMenuToggle,
  onLinkClick,
  renderMobileLinksOnly = false,
  mobileMenuContent
}) => {
  const { theme } = useTheme();
  const textClasses = getThemeTextClasses(theme.theme_layout_mode);
  const mobileMenuContainerRef = useRef<HTMLDivElement>(null);
  const mobileMenuDropdownRef = useRef<HTMLDivElement>(null);
  
  // Handle click outside for the portal-rendered dropdown
  // Note: We don't use useClickOutside here because the dropdown is rendered via portal
  React.useEffect(() => {
    if (!isMobileMenuOpen) return;

    const handleClickOutside = (event: MouseEvent | TouchEvent) => {
      const target = event.target as Node;
      const targetElement = target as Element;
      
      // Check if click is on a link - if so, don't close (let navigation happen)
      const linkElement = targetElement.closest('a');
      if (linkElement && mobileMenuDropdownRef.current?.contains(linkElement)) {
        return; // Let the link handle navigation
      }
      
      // Check if click is inside the dropdown menu
      if (mobileMenuDropdownRef.current?.contains(target)) {
        return; // Don't close if clicking inside menu
      }
      
      // Check if click is on the menu button
      if (mobileMenuContainerRef.current?.contains(target)) {
        return; // Don't close if clicking the menu button
      }
      
      // Close menu if clicking outside
      onMobileMenuToggle();
    };

    // Use a delay to avoid interfering with link clicks
    // This ensures link navigation happens before the handler is active
    const timeoutId = setTimeout(() => {
      document.addEventListener('mousedown', handleClickOutside);
      document.addEventListener('touchstart', handleClickOutside);
    }, 300);

    return () => {
      clearTimeout(timeoutId);
      document.removeEventListener('mousedown', handleClickOutside);
      document.removeEventListener('touchstart', handleClickOutside);
    };
  }, [isMobileMenuOpen, onMobileMenuToggle]);
  
  const handleLinkClick = () => {
    if (onLinkClick) {
      onLinkClick();
    }
  };

  // If only rendering mobile links (for use inside Header's mobile menu container)
  if (renderMobileLinksOnly) {
    return (
      <>
        {navLinks.map((link) => (
          <Link
            key={link.to}
            to={link.to}
            onClick={handleLinkClick}
            className={`px-4 py-3 ${textClasses.primary}/90 
              hover:bg-[var(--luxury-gold)]/10 hover:text-[var(--luxury-gold)] 
              rounded-sm transition-all duration-300 
              border-l-2 border-transparent 
              hover:border-[var(--luxury-gold)] font-light tracking-wide`}
          >
            {link.label}
          </Link>
        ))}
      </>
    );
  }

  return (
    <div className="relative" ref={mobileMenuContainerRef}>
      {/* Desktop Navigation */}
      <nav className="hidden md:flex items-center space-x-2">
        {navLinks.map((link) => (
          <Link
            key={link.to}
            to={link.to}
            className={`${textClasses.primary}/95 hover:text-[var(--luxury-gold)] 
              transition-all duration-300 font-light px-5 py-2.5 
              relative group tracking-wider text-sm uppercase`}
          >
            <span className="relative z-10 transition-all duration-300 group-hover:tracking-widest">
              {link.label}
            </span>
            {/* Underline effect */}
            <span className="absolute bottom-0 left-0 w-0 h-[1px] bg-gradient-to-r from-[var(--luxury-gold)] to-[var(--luxury-gold-light)] group-hover:w-full transition-all duration-500"></span>
            {/* Background glow on hover */}
            <span className="absolute inset-0 bg-gradient-to-r from-[rgba(var(--luxury-gold-rgb),0.05)] via-[rgba(var(--luxury-gold-rgb),0.1)] to-[rgba(var(--luxury-gold-rgb),0.05)] opacity-0 group-hover:opacity-100 transition-opacity duration-300 rounded-sm"></span>
            {/* Subtle border on hover */}
            <span className="absolute inset-0 border border-[rgba(var(--luxury-gold-rgb),0.1)] rounded-sm opacity-0 group-hover:opacity-100 transition-opacity duration-300"></span>
          </Link>
        ))}
      </nav>

      {/* Mobile Menu Button */}
      <button
        onClick={onMobileMenuToggle}
        className="md:hidden p-3 rounded-lg 
          bg-[rgba(var(--luxury-gold-rgb),0.1)] hover:bg-[rgba(var(--luxury-gold-rgb),0.2)] 
          border border-[rgba(var(--luxury-gold-rgb),0.3)] 
          hover:border-[rgba(var(--luxury-gold-rgb),0.5)] transition-all duration-300
          group shadow-lg"
        aria-label="Toggle menu"
      >
        {isMobileMenuOpen ? (
          <X className="w-6 h-6 text-[var(--luxury-gold)] transition-transform duration-300 group-hover:rotate-90" />
        ) : (
          <Menu className="w-6 h-6 text-[var(--luxury-gold)] group-hover:text-[var(--luxury-gold-light)] transition-colors duration-300" />
        )}
      </button>

      {/* Mobile Menu Backdrop and Dropdown - Rendered via Portal */}
      {isMobileMenuOpen && typeof document !== 'undefined' && createPortal(
        <>
          {/* Mobile Menu Backdrop */}
          <div 
            className={`md:hidden fixed inset-0 ${theme.theme_layout_mode === 'light' ? 'bg-black/40' : 'bg-black/70'} backdrop-blur-sm`}
            style={{ 
              top: '73px',
              zIndex: 99998,
              position: 'fixed',
              pointerEvents: 'auto'
            } as React.CSSProperties}
            onClick={(e) => {
              // Only close if clicking directly on backdrop, not on dropdown content
              const target = e.target as HTMLElement;
              if (target === e.currentTarget) {
                onMobileMenuToggle();
              }
            }}
            onTouchStart={(e) => {
              // Prevent backdrop from interfering with touch events on links
              const target = e.target as HTMLElement;
              if (mobileMenuDropdownRef.current?.contains(target)) {
                e.stopPropagation();
              }
            }}
          />

          {/* Mobile Menu Dropdown - Right side on mobile */}
          <div 
            ref={mobileMenuDropdownRef}
            className={`md:hidden fixed top-[73px] right-0 w-80 max-w-[85vw]
              ${theme.theme_layout_mode === 'light' 
                ? 'bg-gradient-to-b from-white via-gray-50 to-white' 
                : 'bg-gradient-to-b from-[#0f0f0f] via-[#1a1a1a] to-[#0f0f0f]'} 
              shadow-[0_8px_32px_rgba(0,0,0,0.9),_-4px_0_20px_rgba(var(--luxury-gold-rgb),0.2)] 
              py-4 border-l-2 border-[rgba(var(--luxury-gold-rgb),0.4)] 
              backdrop-blur-xl animate-fade-in
              overflow-y-auto h-[calc(100vh-73px)]`}
            style={{
              zIndex: 99999,
              position: 'fixed',
              touchAction: 'auto',
              pointerEvents: 'auto'
            } as React.CSSProperties}
            onClick={(e) => {
              // Stop propagation to prevent backdrop from closing menu when clicking inside
              e.stopPropagation();
            }}
            onTouchStart={(e) => {
              // Stop touch events from propagating to backdrop
              e.stopPropagation();
            }}
            onTouchEnd={(e) => {
              // Stop touch end events from propagating
              e.stopPropagation();
            }}
          >
            <div className="flex flex-col space-y-1 px-2">
              {navLinks.map((link) => (
                <Link
                  key={link.to}
                  to={link.to}
                  onClick={(e) => {
                    // Stop propagation to prevent backdrop from closing menu
                    e.stopPropagation();
                    
                    // Close mobile menu after navigation starts
                    setTimeout(() => {
                      if (handleLinkClick) {
                        handleLinkClick();
                      }
                    }, 150);
                  }}
                  onTouchStart={(e) => {
                    // Stop touch events from propagating to backdrop
                    e.stopPropagation();
                  }}
                  onTouchEnd={(e) => {
                    // Ensure touch end doesn't trigger backdrop
                    e.stopPropagation();
                  }}
                  onMouseDown={(e) => {
                    // Ensure mouse events work
                    e.stopPropagation();
                  }}
                  className={`px-4 py-3.5 ${textClasses.primary}/95 
                    hover:bg-[rgba(var(--luxury-gold-rgb),0.15)] hover:text-[var(--luxury-gold)] 
                    rounded-md transition-all duration-300 
                    border-l-2 border-transparent 
                    hover:border-[var(--luxury-gold)] font-light tracking-wider text-sm uppercase
                    group relative mx-2 cursor-pointer text-left w-full block`}
                  style={{ 
                    touchAction: 'manipulation',
                    WebkitTapHighlightColor: 'transparent',
                    pointerEvents: 'auto'
                  }}
                >
                  <span 
                    className="relative z-10"
                    style={{ pointerEvents: 'none' }}
                  >
                    {link.label}
                  </span>
                  <span 
                    className="absolute left-0 top-0 bottom-0 w-0 bg-gradient-to-r from-[rgba(var(--luxury-gold-rgb),0.15)] to-transparent group-hover:w-full transition-all duration-300 rounded-md"
                    style={{ pointerEvents: 'none' }}
                  ></span>
                </Link>
              ))}
              {mobileMenuContent && (
                <>
                  <div className="border-t border-[var(--luxury-gold)]/20 my-2"></div>
                  {mobileMenuContent}
                </>
              )}
            </div>
          </div>
        </>,
        document.body
      )}
    </div>
  );
};

export default Navbar;

