'use client';

import { useState, useEffect, useRef, useCallback, useMemo } from 'react';
import Image from 'next/image';
import { useRouter } from 'next/navigation';
import { useSearch } from '../../context/SearchContext';
import { BookOpen, Award, Search, Globe, ChevronDown, Zap, Building } from 'lucide-react';

// Static data to prevent re-renders
const Hero = () => {
  // Search states - minimized
  const [type, setType] = useState('university');
  const [country, setCountry] = useState('All Country');
  const [search, setSearch] = useState('');
  const [qualification, setQualification] = useState("All Qualifications");
  const [qualifications, setQualifications] = useState<Array<{id: string, title: string}>>([]);
  const [countries, setCountries] = useState<Array<{country: string}>>([]);

  // Live search states - debounced
  const [liveResults, setLiveResults] = useState<any[]>([]);
  const [showLiveResults, setShowLiveResults] = useState(false);
  const [isLoadingLive, setIsLoadingLive] = useState(false);
  const [isLoading, setIsLoading] = useState(false);

  const router = useRouter();
  const inputRef = useRef<HTMLInputElement>(null);
  const searchBarRef = useRef<HTMLDivElement>(null);
  const { selectedCountry, setSelectedCountry, selectedType, setSelectedType } = useSearch();

  // Fetch qualifications and countries - optimized
  useEffect(() => {
    const fetchInitialData = async () => {
      try {
        // Fetch qualifications
        const qualRes = await fetch("/api/frontend/getpostlevel", { method: "POST" });
        if (qualRes.ok) {
          const qualData = await qualRes.json();
          if (qualData.success && qualData.data) {
            setQualifications(qualData.data);
          }
        }

        // Fetch countries
        const countryRes = await fetch('/api/frontend/getcountries', { method: "POST" });
        if (countryRes.ok) {
          const countryData = await countryRes.json();
          if (countryData.success && countryData.data) {
            setCountries(countryData.data);
          }
        }
      } catch (error) {
        console.error("Error fetching initial data:", error);
      }
    };

    fetchInitialData();
  }, []);

  // Sync with context
  useEffect(() => {
    if (selectedCountry !== country) setCountry(selectedCountry);
  }, [selectedCountry, country]);

  useEffect(() => {
    if (selectedType !== type) setType(selectedType);
  }, [selectedType, type]);

  // Handle click outside search
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (searchBarRef.current && !searchBarRef.current.contains(event.target as Node)) {
        setShowLiveResults(false);
      }
    };

    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, []);

  // Debounced live search - optimized
  useEffect(() => {
    const controller = new AbortController();
    
    const performLiveSearch = async () => {
      if (!search.trim() || search.length < 2) {
        setLiveResults([]);
        setShowLiveResults(false);
        return;
      }

      setIsLoadingLive(true);
      try {
        const params = new URLSearchParams({
          search: search,
          type: type === 'all' ? 'all' : type,
          country: country !== 'All Country' ? country : '',
          qualification: qualification !== 'All Qualifications' ? qualification : '',
          page: '1',
          limit: '5'
        });

        const res = await fetch(`/api/frontend/search?${params.toString()}`, {
          signal: controller.signal
        });
        
        if (res.ok) {
          const data = await res.json();
          if (data.success && data.data) {
            setLiveResults(data.data);
            setShowLiveResults(true);
          } else {
            setLiveResults([]);
          }
        }
      } catch (error: any) {
        if (error.name !== 'AbortError') {
          console.error('Error fetching live search results:', error);
          setLiveResults([]);
        }
      } finally {
        setIsLoadingLive(false);
      }
    };

    const debounceTimer = setTimeout(performLiveSearch, 300);
    return () => {
      clearTimeout(debounceTimer);
      controller.abort();
    };
  }, [search, type, country, qualification]);

  const handleSearch = useCallback((e: React.FormEvent) => {
    e.preventDefault();
    if (isLoading) return;

    setIsLoading(true);
    const params = new URLSearchParams();
    if (type) params.append('type', type);
    if (country && country !== 'All Country') params.append('country', country);
    if (qualification && qualification !== "All Qualifications") params.append("qualification", qualification);
    if (search) params.append('q', search);

    router.push(`/search?${params.toString()}`);
    setIsLoading(false);
  }, [isLoading, type, country, qualification, search, router]);

  const handleLiveResultClick = useCallback((item: any, action: 'fill' | 'navigate' = 'fill') => {
    if (action === 'fill') {
      setSearch(item.name);
      setShowLiveResults(false);
      inputRef.current?.focus();
    } else if (action === 'navigate') {
      if (item.type === 'university') {
        router.push(`/university/${item.slug}`);
      } else if (item.type === 'course') {
        router.push(`/courses/${item.id}`);
      }
    }
  }, [router]);

  const handleKeyDown = useCallback((e: React.KeyboardEvent) => {
    if (!showLiveResults || liveResults.length === 0) return;

    if (e.key === 'ArrowDown') {
      e.preventDefault();
    } else if (e.key === 'ArrowUp') {
      e.preventDefault();
    } else if (e.key === 'Enter') {
      e.preventDefault();
      if (search.trim()) {
        handleSearch(e as any);
      }
    }
  }, [showLiveResults, liveResults, search, handleSearch]);

  // Memoized icon getter
  const getItemIcon = useCallback((item: any) => {
    if (item.type === 'university') {
      return <Building className="w-4 h-4 text-blue-500 flex-shrink-0" />;
    } else if (item.type === 'course') {
      return <BookOpen className="w-4 h-4 text-green-500 flex-shrink-0" />;
    }
    return <Search className="w-4 h-4 text-gray-500 flex-shrink-0" />;
  }, []);

  // Memoized search form component
  const SearchForm = useMemo(() => (
    <div className="w-full lg:w-1/2">
      <div 
        ref={searchBarRef}
        className="bg-white/15 backdrop-blur-md rounded-2xl shadow-xl border border-white/20"
      >
        <form onSubmit={handleSearch} className="w-full p-4 sm:p-6">
          <div className="flex flex-col gap-3">
            {/* Type Dropdown */}
            <div className="relative">
              <select
                className="w-full bg-white/20 border border-white/30 text-white rounded-lg py-3 pl-4 pr-10 appearance-none focus:outline-none focus:ring-1 focus:ring-white/50 text-sm sm:text-base"
                value={type}
                onChange={(e) => {
                  setType(e.target.value);
                  setSelectedType(e.target.value);
                  if (e.target.value !== "course") {
                    setQualification("All Qualifications");
                  }
                }}
              >
                <option value="university" className="text-gray-900">Universities</option>
                <option value="course" className="text-gray-900">Courses</option>
                <option value="all" className="text-gray-900">All</option>
              </select>
              <div className="pointer-events-none absolute inset-y-0 right-0 flex items-center pr-3">
                <ChevronDown className="h-4 w-4 text-white/70" />
              </div>
            </div>

            {/* Qualification Dropdown (only when type = course) */}
            {type === "course" && (
              <div className="relative">
                <select
                  className="w-full bg-white/20 border border-white/30 text-white rounded-lg py-3 pl-4 pr-10 appearance-none focus:outline-none focus:ring-1 focus:ring-white/50 text-sm sm:text-base"
                  value={qualification}
                  onChange={(e) => setQualification(e.target.value)}
                >
                  <option value="All Qualifications" className="text-gray-900">
                    All Qualifications
                  </option>
                  {qualifications.map((q) => (
                    <option key={q.id} value={q.id} className="text-gray-900">
                      {q.title}
                    </option>
                  ))}
                </select>
                <div className="pointer-events-none absolute inset-y-0 right-0 flex items-center pr-3">
                  <Award className="h-4 w-4 text-white/70" />
                </div>
              </div>
            )}

            {/* Country Dropdown */}
            <div className="relative">
              <select
                className="w-full bg-white/20 border border-white/30 text-white rounded-lg py-3 pl-4 pr-10 appearance-none focus:outline-none focus:ring-1 focus:ring-white/50 text-sm sm:text-base"
                value={country}
                onChange={(e) => {
                  setCountry(e.target.value);
                  setSelectedCountry(e.target.value);
                }}
              >
                <option value="All Country" className="text-gray-900">All Countries</option>
                {countries.map((countryItem, index) => (
                  <option key={index} value={countryItem.country} className="text-gray-900">
                    {countryItem.country}
                  </option>
                ))}
              </select>
              <div className="pointer-events-none absolute inset-y-0 right-0 flex items-center pr-3">
                <Globe className="h-4 w-4 text-white/70" />
              </div>
            </div>

            {/* Search Input */}
            <div className="relative">
              <div className="relative">
                <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                  <Search className="h-4 w-4 text-white/70" />
                </div>
                <input
                  type="text"
                  ref={inputRef}
                  placeholder="Search University, Course, or Country"
                  className="w-full bg-white/20 border border-white/30 text-white placeholder-white/80 rounded-lg py-3 pl-10 pr-10 focus:outline-none focus:ring-1 focus:ring-white/50 text-sm sm:text-base"
                  value={search}
                  onChange={(e) => setSearch(e.target.value)}
                  onKeyDown={handleKeyDown}
                />
                {search && (
                  <button
                    type="button"
                    className="absolute inset-y-0 right-0 pr-3 flex items-center"
                    onClick={() => {
                      setSearch('');
                      setLiveResults([]);
                      setShowLiveResults(false);
                    }}
                    aria-label="Clear search"
                  >
                    <svg className="h-4 w-4 text-white/70 hover:text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                    </svg>
                  </button>
                )}
              </div>
              
              {/* Live Results - Simplified */}
              {showLiveResults && liveResults.length > 0 && (
                <div className="absolute w-full mt-1 bg-white border border-gray-200 rounded-lg shadow-lg z-50">
                  <ul className="max-h-48 overflow-y-auto py-1">
                    {liveResults.map((item) => (
                      <li
                        key={`${item.type}-${item.id}`}
                        className="px-3 py-2 cursor-pointer hover:bg-gray-50 transition-colors border-b border-gray-100 last:border-b-0"
                        onClick={() => handleLiveResultClick(item, 'navigate')}
                      >
                        <div className="flex items-start gap-2">
                          {getItemIcon(item)}
                          <div className="flex-1 min-w-0">
                            <p className="text-sm font-medium text-gray-800 truncate">
                              {item.name}
                            </p>
                            <div className="flex items-center gap-2 mt-0.5">
                              <span className={`text-xs px-1.5 py-0.5 rounded ${
                                item.type === 'university' 
                                  ? 'bg-blue-100 text-blue-800' 
                                  : 'bg-green-100 text-green-800'
                              }`}>
                                {item.type === 'university' ? 'University' : 'Course'}
                              </span>
                              {item.location && (
                                <span className="text-xs text-gray-500 truncate">
                                  {item.location}
                                </span>
                              )}
                            </div>
                          </div>
                        </div>
                      </li>
                    ))}
                  </ul>
                </div>
              )}
            </div>

            {/* Search Button */}
            <button 
              type="submit" 
              className="w-full bg-gradient-to-r from-yellow-400 to-orange-400 text-gray-900 font-semibold py-3 rounded-lg hover:from-yellow-500 hover:to-orange-500 transition-all duration-300 shadow-lg text-sm sm:text-base"
              disabled={isLoading}
            >
              {isLoading ? (
                <div className="flex items-center justify-center gap-2">
                  <div className="w-3 h-3 border-2 border-gray-900 border-t-transparent rounded-full animate-spin"></div>
                  <span>Searching...</span>
                </div>
              ) : (
                <div className="flex items-center justify-center gap-2">
                  <Search className="w-4 h-4" />
                  <span>Search</span>
                </div>
              )}
            </button>
          </div>
        </form>
      </div>
    </div>
  ), [type, qualification, country, search, isLoading, isLoadingLive, showLiveResults, liveResults, qualifications, countries, handleSearch, handleKeyDown, handleLiveResultClick, getItemIcon, setSelectedType, setSelectedCountry]);

  return (
    <section className="relative min-h-[90vh] flex items-center justify-center overflow-hidden py-8 px-4">
      {/* Background Image - CRITICAL FOR LCP */}
      <div className="absolute top-0 left-0 w-full h-full">
        <Image
          src="/assets/hero2.webp"
          alt="Study abroad background - Find universities and courses worldwide"
          fill
          priority={true}
          sizes="100vw"
          quality={75}
          className="object-cover object-center"
        />
      </div>

      {/* Gradient Overlay - Simplified */}
      <div className="absolute inset-0 bg-gradient-to-br from-[#0B6F78]/30 via-[#0a4d7a]/50 to-[#0a306b]/60"></div>

      {/* Content Container */}
      <div className="relative z-10 w-full max-w-6xl mx-auto">
        <div className="flex flex-col lg:flex-row items-center justify-between gap-8 lg:gap-12">
          
          {/* Text Content */}
          <div className="w-full lg:w-1/2 text-center lg:text-left">
            {/* Badge */}
            <div className="inline-flex items-center bg-white/10 backdrop-blur-sm border border-white/20 rounded-full px-4 py-2 mb-6">
              <Zap className="w-4 h-4 text-yellow-400 mr-2" />
              <span className="text-white font-semibold text-sm">International Education Services</span>
            </div>

            {/* Heading - Critical text content */}
            <h1 className="text-white text-3xl sm:text-4xl lg:text-5xl font-bold leading-tight mb-4">
              Your Global Education Journey{' '}
              <span className="bg-linear-to-r from-yellow-400 to-orange-400 bg-clip-text text-transparent">
                Start Here
              </span>
            </h1>

            {/* Description */}
            <p className="text-white/90 text-lg max-w-2xl mx-auto lg:mx-0 leading-relaxed mb-8">
              Universities Page’s International Education Services help you get direct admission to top universities worldwide. Free application processing, scholarship guidance, and end-to-end support.
            </p>

            {/* Quick Stats - For better engagement */}
            <div className="hidden lg:flex items-center gap-6 mt-8">
              <div className="text-center">
                <div className="text-2xl font-bold text-white">1500+</div>
                <div className="text-sm text-white/80">Universities</div>
              </div>
              <div className="text-center">
                <div className="text-2xl font-bold text-white">100,000+</div>
                <div className="text-sm text-white/80">Courses</div>
              </div>
              <div className="text-center">
                <div className="text-2xl font-bold text-white">50+</div>
                <div className="text-sm text-white/80">Countries</div>
              </div>
            </div>
          </div>

          {/* Search Form */}
          {SearchForm}
        </div>
      </div>

      {/* Optional: Add a loading state for the image */}
      <style jsx>{`
        @keyframes fadeIn {
          from { opacity: 0; }
          to { opacity: 1; }
        }
        
        .hero-image-loaded {
          animation: fadeIn 0.5s ease-in-out;
        }
      `}</style>
    </section>
  );
};

export default Hero;