import React, { useState, useMemo, useEffect, useRef } from 'react';
import { Search, X, ArrowRight, Compass, Ship, Utensils, Anchor, Film } from 'lucide-react';
import { useLanguage } from '../contexts/LanguageContext.tsx';
import { useTheme } from '../contexts/ThemeContext.tsx';
import { CONTENT } from '../constants.ts';
import { useNavigate } from 'react-router-dom';

interface SearchOverlayProps {
  isOpen: boolean;
  onClose: () => void;
}

interface SearchResult {
  title: string;
  subtitle?: string;
  category: 'home' | 'itinerary' | 'ships' | 'dining' | 'activity';
  link: string;
  matchType: 'title' | 'content';
}

const SearchOverlay: React.FC<SearchOverlayProps> = ({ isOpen, onClose }) => {
  const { language } = useLanguage();
  const { itineraries, ships, dining, videoSection } = useTheme();
  const [query, setQuery] = useState('');
  const inputRef = useRef<HTMLInputElement>(null);
  const navigate = useNavigate();

  const t = CONTENT[language];
  const searchT = (CONTENT[language] as any).search || {
    placeholder: "Search...",
    no_results: "No results",
    results_for: "Results: ",
    categories: { home: "Home", ships: "Ships", itinerary: "Trips", dining: "Food", activity: "Fun" }
  };

  // Focus input when opened
  useEffect(() => {
    if (isOpen) {
      setTimeout(() => {
        inputRef.current?.focus();
      }, 100);
      // Removed body scroll lock to keep it feeling lightweight
    } 
  }, [isOpen]);

  // Handle ESC key
  useEffect(() => {
    const handleEsc = (e: KeyboardEvent) => {
      if (e.key === 'Escape') onClose();
    };
    window.addEventListener('keydown', handleEsc);
    return () => window.removeEventListener('keydown', handleEsc);
  }, [onClose]);

  // Build Search Index
  const searchIndex: SearchResult[] = useMemo(() => {
    const index: SearchResult[] = [];

    // 1. Home - Hero (Text on Image)
    index.push({
      title: t.hero.title_normal + ' ' + t.hero.title_italic,
      subtitle: t.hero.subtitle,
      category: 'home',
      link: '/',
      matchType: 'title'
    });

    // 2. Dynamic Itineraries (Cards / Images)
    itineraries.forEach(item => {
      index.push({
        title: item.title,
        subtitle: `${item.route} - ${item.price}`,
        category: 'itinerary',
        link: '/?section=featured-itineraries',
        matchType: 'title'
      });
    });

    // 3. Dynamic Ships (Cards / Images)
    ships.forEach(item => {
      index.push({
        title: item.name,
        subtitle: item.description,
        category: 'ships',
        link: '/?section=our-fleet',
        matchType: 'title'
      });
    });

    // 4. Dynamic Dining (Banner Image)
    index.push({
      title: dining.title,
      subtitle: dining.description,
      category: 'dining',
      link: '/?section=dining-experience',
      matchType: 'title'
    });

    // 5. Dynamic Video/Activity (Thumbnail)
    index.push({
      title: videoSection.title + ' ' + videoSection.titleItalic,
      subtitle: videoSection.description,
      category: 'activity',
      link: '/?section=video-experience',
      matchType: 'title'
    });

    // 6. Ships Page Content (Text on Images: Hero & Cards)
    const shipPage = (t as any).shipsPage;
    if (shipPage) {
        // Hero
        index.push({
            title: shipPage.hero_sub, 
            subtitle: shipPage.hero_desc,
            category: 'ships',
            link: '/ships',
            matchType: 'title'
        });
        // Lanyue Image Card
        index.push({
            title: shipPage.lanyue.title,
            subtitle: shipPage.lanyue.desc,
            category: 'ships',
            link: '/ships?section=lanyue',
            matchType: 'title'
        });
        // Aurora Image Card
        index.push({
            title: shipPage.aurora.title,
            subtitle: shipPage.aurora.desc,
            category: 'ships',
            link: '/ships?section=aurora',
            matchType: 'title'
        });
        // Intro Text
        index.push({
            title: shipPage.intro.title,
            subtitle: shipPage.intro.desc,
            category: 'ships',
            link: '/ships?section=series',
            matchType: 'content'
        });
    }

    return index;
  }, [language, t, itineraries, ships, dining, videoSection]);

  // Filter Results
  const filteredResults = useMemo(() => {
    if (!query.trim()) return [];
    const lowerQuery = query.toLowerCase();
    return searchIndex.filter(item => 
      item.title.toLowerCase().includes(lowerQuery) || 
      (item.subtitle && item.subtitle.toLowerCase().includes(lowerQuery))
    );
  }, [query, searchIndex]);

  const handleResultClick = (link: string) => {
    onClose();
    if (link.startsWith('/?section=')) {
        const sectionId = link.split('=')[1];
        navigate('/');
        setTimeout(() => {
            document.getElementById(sectionId)?.scrollIntoView({ behavior: 'smooth' });
        }, 100);
    } else if (link.startsWith('/ships?section=')) {
        navigate(link);
    } else {
        navigate(link);
    }
  };

  if (!isOpen) return null;

  return (
    // Outer Wrapper: Fully transparent, used for positioning and click-outside detection
    <div 
        className="fixed inset-0 z-[100] flex justify-center items-start pt-[15vh]"
        onClick={onClose}
    >
      {/* 
        Inner Container: 
        - Compact floating bar (capsule/rounded rect style)
        - Background: Semi-transparent dark glass (bg-black/60) to ensure readability
        - Dimensions: Tightly wrapped around text input (w-auto, min-width)
      */}
      <div 
        className="relative w-auto min-w-[300px] md:min-w-[500px] max-w-2xl mx-4 bg-black/60 backdrop-blur-md rounded border border-white/10 shadow-2xl animate-fade-in-up px-4 py-2 flex flex-col" 
        onClick={(e) => e.stopPropagation()}
      >
        <div className="flex items-center w-full">
             <Search className="text-white/60 mr-3 shrink-0" size={18} />
             <input 
                ref={inputRef}
                type="text" 
                value={query}
                onChange={(e) => setQuery(e.target.value)}
                placeholder={searchT.placeholder}
                className="flex-1 bg-transparent border-none text-xl font-serif italic text-white placeholder-white/40 focus:outline-none focus:ring-0 transition-colors tracking-wide h-10 px-0"
            />
             <button 
                onClick={onClose} 
                className="ml-3 text-white/50 hover:text-white transition-colors shrink-0"
            >
                <X size={18} />
            </button>
        </div>

        {/* Results Dropdown - Floating immediately below the bar */}
        {(query.trim() !== '') && (
            <div className="absolute top-full left-0 right-0 mt-2 bg-vista-darkblue/95 backdrop-blur-xl rounded border border-white/10 max-h-[60vh] overflow-y-auto no-scrollbar shadow-2xl">
                 {filteredResults.length > 0 ? (
                    <div className="p-2">
                        <div className="px-4 py-2 text-vista-gold text-[10px] font-bold uppercase tracking-widest border-b border-white/5">
                            {searchT.results_for} "{query}"
                        </div>
                        {filteredResults.map((result, idx) => (
                            <div 
                                key={idx} 
                                onClick={() => handleResultClick(result.link)}
                                className="group flex items-center justify-between p-3 hover:bg-white/10 cursor-pointer transition-colors rounded-sm"
                            >
                                <div className="flex items-center gap-3">
                                    <div className="text-white/40 group-hover:text-vista-gold transition-colors">
                                        {result.category === 'itinerary' && <Compass size={16} />}
                                        {result.category === 'ships' && <Ship size={16} />}
                                        {result.category === 'dining' && <Utensils size={16} />}
                                        {result.category === 'activity' && <Film size={16} />}
                                        {result.category === 'home' && <Anchor size={16} />}
                                    </div>
                                    <div>
                                        <h3 className="text-base font-serif text-white group-hover:text-vista-gold transition-colors">{result.title}</h3>
                                        {result.subtitle && (
                                            <p className="text-white/50 text-[10px] mt-0.5 line-clamp-1">{result.subtitle}</p>
                                        )}
                                    </div>
                                </div>
                                <ArrowRight className="text-white/20 group-hover:text-vista-gold w-3 h-3" />
                            </div>
                        ))}
                    </div>
                 ) : (
                    <div className="p-6 text-center text-white/40 font-serif italic text-base">
                        {searchT.no_results}
                    </div>
                 )}
            </div>
        )}
      </div>
    </div>
  );
};

export default SearchOverlay;