import { useState, useEffect, useRef } from 'react';
import { Link, useLocation } from 'react-router-dom';
import { motion, AnimatePresence } from 'motion/react';
import { Menu, X, Search, ChevronRight } from 'lucide-react';
import { cn } from '@/lib/utils';
import { articles } from '@/data/articles';
import LanguageSelector from './LanguageSelector';

const navLinks = [
  { name: 'Início', path: '/' },
  { name: 'Missão', path: '/about' },
  { name: 'Soluções', path: '/services' },
  { name: 'Cases', path: '/cases' },
  { name: 'Blog', path: '/blog' },
];

export default function Navbar() {
  const [isScrolled, setIsScrolled] = useState(false);
  const [mobileMenuOpen, setMobileMenuOpen] = useState(false);
  const [searchOpen, setSearchOpen] = useState(false);
  const [searchQuery, setSearchQuery] = useState('');
  const location = useLocation();
  const searchInputRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    const handleScroll = () => setIsScrolled(window.scrollY > 10);
    window.addEventListener('scroll', handleScroll);
    return () => window.removeEventListener('scroll', handleScroll);
  }, []);

  useEffect(() => {
    setMobileMenuOpen(false);
    setSearchOpen(false);
    setSearchQuery('');
  }, [location.pathname]);

  useEffect(() => {
    if (searchOpen) setTimeout(() => searchInputRef.current?.focus(), 100);
  }, [searchOpen]);

  // Prevent scroll when mobile menu is open
  useEffect(() => {
    if (mobileMenuOpen || searchOpen) {
      document.body.style.overflow = 'hidden';
    } else {
      document.body.style.overflow = 'unset';
    }
  }, [mobileMenuOpen, searchOpen]);

  const searchResults = searchQuery.length > 1 
    ? articles.filter(a => 
        a.title.toLowerCase().includes(searchQuery.toLowerCase()) || 
        a.excerpt.toLowerCase().includes(searchQuery.toLowerCase()) ||
        a.category.toLowerCase().includes(searchQuery.toLowerCase())
      ).slice(0, 5)
    : [];

  return (
    <>
      <header
        className={cn(
          'fixed inset-x-0 top-0 z-50 transition-all duration-300 border-b border-transparent',
          isScrolled ? 'bg-black/80 backdrop-blur-md border-white/10 py-4' : 'bg-transparent py-4 sm:py-6'
        )}
      >
        <div className="container mx-auto px-6 max-w-7xl">
          <div className="flex items-center justify-between">
            {/* Logo */}
            <Link to="/" className="flex items-center gap-2 group">
              <span className="font-display font-bold text-xl tracking-tighter text-white">
                ONYX
              </span>
              <div className="w-1.5 h-1.5 bg-white rounded-full ml-1" />
            </Link>

            {/* Desktop Nav */}
            <nav className="hidden md:flex items-center gap-8">
              {navLinks.map((link) => (
                <Link
                  key={link.path}
                  to={link.path}
                  className={cn(
                    'text-[13px] font-mono tracking-wide uppercase transition-colors hover:text-white',
                    location.pathname === link.path ? 'text-white' : 'text-gray-500'
                  )}
                >
                  {link.name}
                </Link>
              ))}
            </nav>

            {/* Actions */}
            <div className="flex items-center gap-3 sm:gap-4">
              <div className="hidden md:block">
                 <LanguageSelector />
              </div>
              <button
                onClick={() => setSearchOpen(true)}
                className="flex items-center justify-center text-gray-500 hover:text-white transition-colors w-10 h-10 rounded-full hover:bg-white/5"
              >
                <Search className="w-4 h-4" />
              </button>
              
              <Link
                to="/contact"
                className="hidden md:flex items-center gap-2 bg-white text-black px-5 py-2.5 rounded-none text-xs font-mono uppercase font-bold hover:bg-gray-200 transition-colors"
              >
                Auditoria Gratuita
              </Link>
              
              <button
                className="md:hidden text-gray-400 hover:text-white flex items-center justify-center w-10 h-10"
                onClick={() => setMobileMenuOpen(true)}
              >
                <Menu className="w-5 h-5" />
              </button>
            </div>
          </div>
        </div>
      </header>

      {/* Search Overlay */}
      <AnimatePresence>
        {searchOpen && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="fixed inset-0 z-[70] bg-black backdrop-blur-md flex items-start justify-center pt-24 px-4"
            onClick={() => setSearchOpen(false)}
          >
            <motion.div
              initial={{ opacity: 0, scale: 0.95, y: -20 }}
              animate={{ opacity: 1, scale: 1, y: 0 }}
              exit={{ opacity: 0, scale: 0.95, y: -20 }}
              className="w-full max-w-2xl bg-black border border-white/10 shadow-2xl overflow-hidden flex flex-col max-h-[80vh]"
              onClick={(e) => e.stopPropagation()}
            >
              <div className="flex items-center border-b border-white/10 px-4 py-4">
                <Search className="w-5 h-5 text-gray-500 mr-3" />
                <input
                  ref={searchInputRef}
                  type="text"
                  placeholder="Pesquisar artigos e tópicos..."
                  className="flex-1 bg-transparent border-none text-white focus:outline-none text-base font-mono placeholder:text-gray-700"
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                />
                <button 
                  onClick={() => setSearchOpen(false)}
                  className="text-gray-500 hover:text-white p-2"
                >
                  <X className="w-5 h-5" />
                </button>
              </div>

              {searchQuery.length > 1 && (
                <div className="overflow-y-auto flex-1 p-2">
                  {searchResults.length > 0 ? (
                    <div className="flex flex-col gap-1">
                      {searchResults.map(result => (
                         <Link 
                           key={result.id} 
                           to={`/blog/${result.slug}`}
                           className="flex items-center gap-4 p-4 border border-transparent hover:border-white/10 hover:bg-white/5 transition-colors group"
                         >
                           <div className="flex flex-col flex-1 overflow-hidden">
                              <div className="flex items-center justify-between gap-2 mb-1">
                                <span className="font-sans font-medium text-white text-sm truncate">{result.title}</span>
                                <span className="text-[10px] text-gray-400 font-mono tracking-widest uppercase">{result.category}</span>
                              </div>
                              <span className="text-sm text-gray-500 truncate">{result.excerpt}</span>
                           </div>
                           <ChevronRight className="w-4 h-4 text-gray-600 group-hover:text-white transition-colors" />
                         </Link>
                      ))}
                    </div>
                  ) : (
                    <div className="py-12 px-4 text-center border-t border-white/5">
                      <p className="text-gray-600 mb-2 font-mono text-sm uppercase tracking-widest">Aguardando sinais...</p>
                    </div>
                  )}
                </div>
              )}
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>

      {/* Mobile Menu */}
      <AnimatePresence>
        {mobileMenuOpen && (
          <motion.div
            initial={{ opacity: 0, y: '-100%' }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: '-100%' }}
            transition={{ type: 'spring', damping: 25, stiffness: 200 }}
            className="fixed inset-0 z-[100] bg-black flex flex-col pt-20"
          >
            <div className="absolute top-0 inset-x-0 flex items-center justify-between p-4 sm:p-6 border-b border-white/10">
              <span className="font-display font-bold text-xl tracking-tighter text-white">
                ONYX
              </span>
              <div className="flex items-center gap-2">
                 <LanguageSelector />
                 <button
                   onClick={() => setMobileMenuOpen(false)}
                   className="w-10 h-10 flex items-center justify-center text-white bg-white/5 rounded-full"
                 >
                   <X className="w-5 h-5" />
                 </button>
              </div>
            </div>
            
            <div className="flex-1 py-12 px-6 flex flex-col justify-center gap-8 overflow-y-auto">
              <nav className="flex flex-col gap-6">
                {navLinks.map((link) => (
                  <Link
                    key={link.path}
                    to={link.path}
                    className="text-4xl font-display font-medium text-gray-400 hover:text-white transition-colors"
                  >
                    {link.name}
                  </Link>
                ))}
              </nav>
              
              <div className="mt-12 pt-8 border-t border-white/10">
                <Link
                  to="/contact"
                  className="block w-full bg-white text-black px-6 py-4 text-center font-mono uppercase tracking-widest text-sm font-bold"
                >
                  Solicitar Auditoria
                </Link>
              </div>
            </div>
          </motion.div>
        )}
      </AnimatePresence>
    </>
  );
}
