import { useState, useRef, useEffect } from 'react';
import { Link, useLocation } from 'react-router-dom';
import { motion, AnimatePresence } from 'framer-motion';
import { cn } from '@/lib/utils';
import { useSettings } from '@/contexts/SettingsContext';
import { ChevronDown, Menu } from 'lucide-react';

const navItems = [
  { path: '/', label: 'Home' },
  { path: '/about', label: 'About Me' },
  { path: '/projects', label: 'Projects' },
  { path: '/resources', label: 'Resources' },
  { path: '/links', label: 'Links' },
  { path: '/ai', label: 'AI Chat' },
  { path: '/music', label: 'Music Player' },
  { path: '/games', label: 'Arcade' },
  { path: '/achievements', label: 'Achievements' },
  { path: '/faq', label: 'FAQ' },
];

const Sidebar = () => {
  const location = useLocation();
  const { playSound } = useSettings();
  const [isExpanded, setIsExpanded] = useState(false);
  const [showFooter, setShowFooter] = useState(true);
  const navRef = useRef<HTMLElement>(null);
  const footerRef = useRef<HTMLDivElement>(null);
  const sidebarRef = useRef<HTMLElement>(null);

  const currentPage = navItems.find(item => item.path === location.pathname)?.label || 'Menu';

  // Close mobile menu when route changes
  useEffect(() => {
    setIsExpanded(false);
  }, [location.pathname]);

  // Check if footer is visible within the sidebar
  useEffect(() => {
    const checkFooterVisibility = () => {
      if (!sidebarRef.current || !footerRef.current || !navRef.current) return;
      
      const sidebarRect = sidebarRef.current.getBoundingClientRect();
      const navHeight = navRef.current.scrollHeight;
      const footerHeight = footerRef.current.offsetHeight;
      const availableHeight = sidebarRect.height;
      
      // Calculate if there's enough space for nav items + footer
      const totalContentHeight = navHeight + footerHeight + 32; // 32px for padding
      setShowFooter(totalContentHeight <= availableHeight);
    };

    checkFooterVisibility();
    window.addEventListener('resize', checkFooterVisibility);
    return () => window.removeEventListener('resize', checkFooterVisibility);
  }, []);

  const toggleMenu = () => {
    setIsExpanded(!isExpanded);
    playSound('click');
  };

  return (
    <aside 
      ref={sidebarRef}
      className="w-full md:w-[230px] lg:w-[250px] h-auto md:h-full flex flex-col border-b-2 md:border-b-0 md:border-r-2 border-primary bg-background/70 box-glow shrink-0"
    >
      {/* Mobile Toggle Header */}
      <button
        onClick={toggleMenu}
        className="md:hidden flex items-center justify-between w-full p-4 font-minecraft text-lg text-primary text-glow"
      >
        <div className="flex items-center gap-2">
          <Menu size={20} />
          <span>{currentPage}</span>
        </div>
        <motion.div
          animate={{ rotate: isExpanded ? 180 : 0 }}
          transition={{ duration: 0.2 }}
        >
          <ChevronDown size={20} />
        </motion.div>
      </button>

      {/* Desktop Navigation - Always visible */}
      <nav ref={navRef} className="hidden md:flex flex-col flex-grow p-4 md:p-5 overflow-y-auto scrollbar-thin scrollbar-thumb-primary/50 scrollbar-track-transparent">
        {navItems.map((item, index) => {
          const isActive = location.pathname === item.path;
          
          return (
            <motion.div
              key={item.path}
              initial={{ opacity: 0, x: -20 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ delay: index * 0.1 }}
            >
              <Link
                to={item.path}
                onClick={() => playSound('click')}
                onMouseEnter={() => playSound('hover')}
                className={cn(
                  "group relative block py-4 px-4 font-minecraft text-lg text-primary border-b border-primary/30",
                  "transition-all duration-300 text-glow",
                  "hover:bg-primary/20 hover:scale-105 hover:box-glow",
                  isActive && "bg-primary/20 box-glow"
                )}
              >
                {item.label}
                <span className="absolute right-4 text-primary animate-blink opacity-0 transition-opacity duration-200 group-hover:opacity-100 pointer-events-none">
                  {'>_'}
                </span>
              </Link>
            </motion.div>
          );
        })}
        
        {/* Inline footer when sidebar is too short - folded into nav */}
        {!showFooter && (
          <div className="mt-auto pt-4 border-t border-primary/30">
            <p className="font-pixel text-sm text-primary text-glow text-center">
              Access Granted
            </p>
          </div>
        )}
      </nav>

      {/* Mobile Navigation - Collapsible */}
      <AnimatePresence>
        {isExpanded && (
          <motion.nav
            initial={{ height: 0, opacity: 0 }}
            animate={{ height: 'auto', opacity: 1 }}
            exit={{ height: 0, opacity: 0 }}
            transition={{ duration: 0.2 }}
            className="md:hidden overflow-hidden border-t border-primary/30"
          >
            {navItems.map((item, index) => {
              const isActive = location.pathname === item.path;
              
              return (
                <motion.div
                  key={item.path}
                  initial={{ opacity: 0, x: -20 }}
                  animate={{ opacity: 1, x: 0 }}
                  transition={{ delay: index * 0.05 }}
                >
                  <Link
                    to={item.path}
                    onClick={(e) => {
                      playSound('click');
                      // Immediately close the menu
                      setIsExpanded(false);
                    }}
                    className={cn(
                      "group relative block py-3 px-4 font-minecraft text-base text-primary border-b border-primary/30",
                      "transition-all duration-300 text-glow",
                      "hover:bg-primary/20",
                      isActive && "bg-primary/20 box-glow"
                    )}
                  >
                    {item.label}
                    <span className="absolute right-4 text-primary animate-blink opacity-0 transition-opacity duration-200 group-hover:opacity-100 pointer-events-none">
                      {'>_'}
                    </span>
                  </Link>
                </motion.div>
              );
            })}
          </motion.nav>
        )}
      </AnimatePresence>
      
      {/* Desktop Footer - Only shown if visible */}
      {showFooter && (
        <div ref={footerRef} className="hidden md:block p-4 border-t border-primary/30">
          <p className="font-pixel text-sm text-primary text-glow text-center">
            Access Granted
          </p>
        </div>
      )}
    </aside>
  );
};

export default Sidebar;
