// components/EnhancedStandardSearchForm.tsx
'use client';

import { 
  Search, Filter, MapPin, Globe, Monitor, DollarSign, 
  Star, Clock, Users, Target, Languages, Briefcase,
  GraduationCap, Plane, Home, TrendingUp, Zap,
  ChevronDown, X, RefreshCw, Shield, CheckCircle,
  Loader2, Navigation, Building, Check
} from 'lucide-react';
import { useState, useEffect, useCallback } from 'react';
import debounce from 'lodash/debounce';

interface EnhancedStandardSearchFormProps {
  filters: {
    country: string;
    city: string;
    digital_only: boolean;
    exact_match: boolean;
    min_rating: number;
    max_price: number;
    specialization: string[];
    services: string[];
  };
  onChange: (filters: any) => void;
  onSearch: () => void;
}

// External API services
const COUNTRIES_API = 'https://restcountries.com/v3.1';
const GEOAPIFY_API = process.env.NEXT_PUBLIC_GEOAPIFY_API_KEY || '';
const GEOAPIFY_URL = 'https://api.geoapify.com/v1/geocode/autocomplete';

export default function EnhancedStandardSearchForm({ 
  filters, 
  onChange, 
  onSearch 
}: EnhancedStandardSearchFormProps) {
  const [countrySuggestions, setCountrySuggestions] = useState<any[]>([]);
  const [citySuggestions, setCitySuggestions] = useState<any[]>([]);
  const [showCountrySuggestions, setShowCountrySuggestions] = useState(false);
  const [showCitySuggestions, setShowCitySuggestions] = useState(false);
  const [loadingCountries, setLoadingCountries] = useState(false);
  const [loadingCities, setLoadingCities] = useState(false);
  const [countryInput, setCountryInput] = useState(filters.country);
  const [cityInput, setCityInput] = useState(filters.city);

  // Fetch country suggestions
  const fetchCountrySuggestions = useCallback(
    debounce(async (query: string) => {
      if (!query.trim() || query.length < 2) {
        setCountrySuggestions([]);
        return;
      }

      setLoadingCountries(true);
      try {
        const response = await fetch(`${COUNTRIES_API}/name/${encodeURIComponent(query)}?fields=name,flags,cca2`);
        if (response.ok) {
          const data = await response.json();
          setCountrySuggestions(data.slice(0, 10)); // Limit to 10 suggestions
        }
      } catch (error) {
        console.error('Error fetching countries:', error);
      } finally {
        setLoadingCountries(false);
      }
    }, 300),
    []
  );

  // Fetch city suggestions
  const fetchCitySuggestions = useCallback(
    debounce(async (query: string) => {
      if (!query.trim() || query.length < 2) {
        setCitySuggestions([]);
        return;
      }

      if (!GEOAPIFY_API) {
        // Fallback to local cities if API key not configured
        const localCities = [
          'Lahore, Pakistan', 'Karachi, Pakistan', 'Islamabad, Pakistan',
          'Rawalpindi, Pakistan', 'Faisalabad, Pakistan', 'Multan, Pakistan',
          'Gujranwala, Pakistan', 'Peshawar, Pakistan', 'Quetta, Pakistan',
          'Hyderabad, Pakistan', 'Delhi, India', 'Mumbai, India',
          'Dubai, UAE', 'London, UK', 'Toronto, Canada',
          'Sydney, Australia', 'New York, USA', 'Berlin, Germany'
        ].filter(city => city.toLowerCase().includes(query.toLowerCase()));
        
        setCitySuggestions(localCities.map(city => ({ 
          formatted: city,
          cityOnly: city.split(',')[0].trim()
        })));
        return;
      }

      setLoadingCities(true);
      try {
        const response = await fetch(
          `${GEOAPIFY_URL}?text=${encodeURIComponent(query)}&apiKey=${GEOAPIFY_API}&limit=10&type=city`
        );
        
        if (response.ok) {
          const data = await response.json();
          const formattedFeatures = data.features?.map((feature: any) => {
            const props = feature.properties;
            return {
              ...props,
              formatted: props.formatted,
              cityOnly: props.city || props.formatted.split(',')[0].trim()
            };
          }) || [];
          setCitySuggestions(formattedFeatures);
        }
      } catch (error) {
        console.error('Error fetching cities:', error);
      } finally {
        setLoadingCities(false);
      }
    }, 300),
    []
  );

  // Handle country input change
  const handleCountryInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value;
    setCountryInput(value);
    onChange({ ...filters, country: value });
    fetchCountrySuggestions(value);
    setShowCountrySuggestions(true);
  };

  // Handle city input change
  const handleCityInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value;
    setCityInput(value);
    // Extract city name from input for the payload
    const cityOnly = value.split(',')[0].trim();
    onChange({ ...filters, city: cityOnly });
    fetchCitySuggestions(value);
    setShowCitySuggestions(true);
  };

  // Select country from suggestions
  const selectCountry = (country: any) => {
    const countryName = country.name.common;
    setCountryInput(countryName);
    onChange({ ...filters, country: countryName });
    setShowCountrySuggestions(false);
    setCountrySuggestions([]);
  };

  // Select city from suggestions - UPDATED to send only city name
  const selectCity = (city: any) => {
    let displayName = '';
    let cityName = '';
    
    if (typeof city === 'string') {
      // If it's a string (from local fallback)
      displayName = city;
      cityName = city.split(',')[0].trim();
    } else if (city.formatted) {
      // If from Geoapify API or local fallback with formatted property
      displayName = city.formatted;
      cityName = city.cityOnly || city.formatted.split(',')[0].trim();
    } else if (city.name) {
      displayName = city.name;
      cityName = city.name.split(',')[0].trim();
    }
    
    // Show full formatted name in input for better UX
    setCityInput(displayName);
    // Send only city name to filters payload
    onChange({ ...filters, city: cityName });
    setShowCitySuggestions(false);
    setCitySuggestions([]);
  };

  // Clear country field
  const clearCountry = () => {
    setCountryInput('');
    onChange({ ...filters, country: '' });
    setCountrySuggestions([]);
  };

  // Clear city field
  const clearCity = () => {
    setCityInput('');
    onChange({ ...filters, city: '' });
    setCitySuggestions([]);
  };

  // Popular countries for quick selection
  const popularCountries = [
    { name: 'Germany', flag: '🇩🇪', code: 'DE' },
    { name: 'Canada', flag: '🇨🇦', code: 'CA' },
    { name: 'USA', flag: '🇺🇸', code: 'US' },
    { name: 'UK', flag: '🇬🇧', code: 'GB' },
    { name: 'Australia', flag: '🇦🇺', code: 'AU' },
    { name: 'UAE', flag: '🇦🇪', code: 'AE' },
  ];

  // Popular cities for quick selection - UPDATED structure
  const popularCities = [
    { name: 'Lahore', fullName: 'Lahore, Pakistan', icon: '🏙️' },
    { name: 'Karachi', fullName: 'Karachi, Pakistan', icon: '🌊' },
    { name: 'Islamabad', fullName: 'Islamabad, Pakistan', icon: '🏔️' },
    { name: 'Delhi', fullName: 'Delhi, India', icon: '🕌' },
    { name: 'Dubai', fullName: 'Dubai, UAE', icon: '🏙️' },
    { name: 'London', fullName: 'London, UK', icon: '🇬🇧' },
  ];

  // Close suggestion dropdowns when clicking outside
  useEffect(() => {
    const handleClickOutside = (e: MouseEvent) => {
      const target = e.target as HTMLElement;
      if (!target.closest('.country-suggestions') && !target.closest('input[placeholder*="countries"]')) {
        setShowCountrySuggestions(false);
      }
      if (!target.closest('.city-suggestions') && !target.closest('input[placeholder*="cities"]')) {
        setShowCitySuggestions(false);
      }
    };

    document.addEventListener('click', handleClickOutside);
    return () => document.removeEventListener('click', handleClickOutside);
  }, []);

  return (
    <div className="space-y-6">
      {/* Target Country - Enhanced with Autocomplete */}
      <div className="space-y-2">
        <label className="flex items-center gap-2 text-sm font-semibold text-gray-800">
          <Globe className="w-4 h-4 text-blue-600" />
          Target Country
        </label>
        
        <div className="relative">
          <div className="relative">
            <input
              type="text"
              value={countryInput}
              onChange={handleCountryInputChange}
              onFocus={() => setShowCountrySuggestions(true)}
              placeholder="Type to search countries..."
              className="w-full p-4 pl-12 border-2 border-gray-300 rounded-xl focus:border-blue-500 focus:ring-4 focus:ring-blue-100 text-gray-700 placeholder-gray-400 transition-all"
            />
            <div className="absolute left-4 top-1/2 -translate-y-1/2 pointer-events-none">
              <Globe className="w-5 h-5 text-gray-400" />
            </div>
            {countryInput && (
              <button
                type="button"
                onClick={clearCountry}
                className="absolute right-4 top-1/2 -translate-y-1/2 p-1 hover:bg-gray-100 rounded-full transition-colors"
              >
                <X className="w-4 h-4 text-gray-400" />
              </button>
            )}
          </div>

          {/* Country Suggestions Dropdown */}
          {showCountrySuggestions && (
            <div className="absolute z-50 w-full mt-1 bg-white border border-gray-200 rounded-xl shadow-2xl max-h-96 overflow-y-auto country-suggestions">
              {loadingCountries ? (
                <div className="p-4 text-center">
                  <Loader2 className="w-5 h-5 animate-spin mx-auto text-blue-600" />
                  <p className="text-sm text-gray-500 mt-2">Searching countries...</p>
                </div>
              ) : countrySuggestions.length > 0 ? (
                <div className="py-2">
                  <div className="px-3 py-2 text-xs font-semibold text-gray-500 uppercase tracking-wider">
                    Search Results
                  </div>
                  {countrySuggestions.map((country) => (
                    <button
                      key={country.cca2}
                      type="button"
                      onClick={() => selectCountry(country)}
                      className="w-full px-4 py-3 flex items-center gap-3 hover:bg-blue-50 transition-colors text-left"
                    >
                      <span className="text-2xl">{country.flags?.emoji || '🌍'}</span>
                      <div className="flex-1">
                        <div className="font-medium text-gray-900">{country.name.common}</div>
                        <div className="text-xs text-gray-500">{country.name.official}</div>
                      </div>
                      {countryInput === country.name.common && (
                        <Check className="w-4 h-4 text-green-500" />
                      )}
                    </button>
                  ))}
                </div>
              ) : countryInput.length >= 2 ? (
                <div className="p-4 text-center text-gray-500">
                  No countries found for {countryInput}
                </div>
              ) : null}

              {/* Popular Countries */}
              {(!countryInput || countryInput.length < 2) && (
                <div className="border-t border-gray-100">
                  <div className="px-3 py-2 text-xs font-semibold text-gray-500 uppercase tracking-wider">
                    Popular Countries
                  </div>
                  <div className="grid grid-cols-2 gap-1 p-2">
                    {popularCountries.map((country) => (
                      <button
                        key={country.code}
                        type="button"
                        onClick={() => {
                          setCountryInput(country.name);
                          onChange({ ...filters, country: country.name });
                          setShowCountrySuggestions(false);
                        }}
                        className={`px-3 py-2 rounded-lg flex items-center gap-2 transition-all ${
                          countryInput === country.name
                            ? 'bg-blue-100 text-blue-700 border border-blue-200'
                            : 'hover:bg-gray-100 text-gray-700'
                        }`}
                      >
                        <span className="text-lg">{country.flag}</span>
                        <span className="font-medium">{country.name}</span>
                      </button>
                    ))}
                  </div>
                </div>
              )}
            </div>
          )}
        </div>
      </div>

      {/* Your City - Enhanced with Autocomplete */}
      <div className="space-y-2">
        <label className="flex items-center gap-2 text-sm font-semibold text-gray-800">
          <MapPin className="w-4 h-4 text-blue-600" />
          Your City
        </label>
        
        <div className="relative">
          <div className="relative">
            <input
              type="text"
              value={cityInput}
              onChange={handleCityInputChange}
              onFocus={() => setShowCitySuggestions(true)}
              placeholder="Type to search cities..."
              className="w-full p-4 pl-12 border-2 border-gray-300 rounded-xl focus:border-blue-500 focus:ring-4 focus:ring-blue-100 text-gray-700 placeholder-gray-400 transition-all"
            />
            <div className="absolute left-4 top-1/2 -translate-y-1/2 pointer-events-none">
              <MapPin className="w-5 h-5 text-gray-400" />
            </div>
            {cityInput && (
              <button
                type="button"
                onClick={clearCity}
                className="absolute right-4 top-1/2 -translate-y-1/2 p-1 hover:bg-gray-100 rounded-full transition-colors"
              >
                <X className="w-4 h-4 text-gray-400" />
              </button>
            )}
          </div>

          {/* City Suggestions Dropdown */}
          {showCitySuggestions && (
            <div className="absolute z-50 w-full mt-1 bg-white border border-gray-200 rounded-xl shadow-2xl max-h-96 overflow-y-auto city-suggestions">
              {loadingCities ? (
                <div className="p-4 text-center">
                  <Loader2 className="w-5 h-5 animate-spin mx-auto text-blue-600" />
                  <p className="text-sm text-gray-500 mt-2">Searching cities...</p>
                </div>
              ) : citySuggestions.length > 0 ? (
                <div className="py-2">
                  <div className="px-3 py-2 text-xs font-semibold text-gray-500 uppercase tracking-wider">
                    Search Results
                  </div>
                  {citySuggestions.map((city, index) => (
                    <button
                      key={index}
                      type="button"
                      onClick={() => selectCity(city)}
                      className="w-full px-4 py-3 flex items-center gap-3 hover:bg-blue-50 transition-colors text-left"
                    >
                      <div className="p-2 bg-gray-100 rounded-lg">
                        <Building className="w-4 h-4 text-gray-600" />
                      </div>
                      <div className="flex-1">
                        <div className="font-medium text-gray-900">
                          {city.formatted || city.name || city}
                        </div>
                        {city.country && (
                          <div className="text-xs text-gray-500 flex items-center gap-1">
                            <Globe className="w-3 h-3" />
                            {city.country}
                          </div>
                        )}
                      </div>
                      {(cityInput === (city.formatted || city.name || city) || 
                       (typeof city === 'string' && cityInput === city) ||
                       (city.formatted && cityInput.startsWith(city.cityOnly))) && (
                        <Check className="w-4 h-4 text-green-500" />
                      )}
                    </button>
                  ))}
                </div>
              ) : cityInput.length >= 2 ? (
                <div className="p-4 text-center text-gray-500">
                  No cities found for {cityInput}
                </div>
              ) : null}

              {/* Popular Cities */}
              {(!cityInput || cityInput.length < 2) && (
                <div className="border-t border-gray-100">
                  <div className="px-3 py-2 text-xs font-semibold text-gray-500 uppercase tracking-wider">
                    Popular Cities
                  </div>
                  <div className="grid grid-cols-2 gap-1 p-2">
                    {popularCities.map((city, index) => (
                      <button
                        key={index}
                        type="button"
                        onClick={() => {
                          setCityInput(city.fullName); // Show full name in UI
                          onChange({ ...filters, city: city.name }); // Send only city name
                          setShowCitySuggestions(false);
                        }}
                        className={`px-3 py-2 rounded-lg flex items-center gap-2 transition-all ${
                          cityInput.startsWith(city.name) || filters.city === city.name
                            ? 'bg-blue-100 text-blue-700 border border-blue-200'
                            : 'hover:bg-gray-100 text-gray-700'
                        }`}
                      >
                        <span className="text-lg">{city.icon}</span>
                        <div className="text-left">
                          <span className="font-medium block">{city.name}</span>
                          <span className="text-xs text-gray-500 truncate">
                            {city.fullName.split(',')[1]?.trim()}
                          </span>
                        </div>
                      </button>
                    ))}
                  </div>
                </div>
              )}
            </div>
          )}
        </div>
      </div>

      {/* Digital Only Toggle */}
      <div className={`p-4 rounded-xl border-2 transition-all duration-300 ${filters.digital_only ? 'border-blue-500 bg-blue-50' : 'border-gray-300 bg-gray-50'}`}>
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-3">
            <div className={`p-2.5 rounded-lg ${filters.digital_only ? 'bg-blue-100' : 'bg-gray-100'}`}>
              <Monitor className={`w-5 h-5 ${filters.digital_only ? 'text-blue-600' : 'text-gray-500'}`} />
            </div>
            <div>
              <h4 className="font-bold text-gray-900">Digital Consultation Only</h4>
              <p className="text-sm text-gray-600">Show consultants available for online meetings</p>
            </div>
          </div>
          <button
            type="button"
            onClick={() => onChange({ ...filters, digital_only: !filters.digital_only })}
            className={`relative inline-flex h-7 w-14 items-center rounded-full transition-all duration-300 ${filters.digital_only ? 'bg-blue-600 shadow-inner' : 'bg-gray-300'}`}
          >
            <span
              className={`inline-block h-5 w-5 transform rounded-full bg-white transition-all duration-300 shadow-lg ${filters.digital_only ? 'translate-x-8' : 'translate-x-1'}`}
            />
          </button>
        </div>
      </div>

      {/* Exact Match Toggle */}
      <div className="p-4 rounded-xl border-2 border-gray-300 bg-gray-50">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-3">
            <div className="p-2.5 rounded-lg bg-gray-100">
              <Target className="w-5 h-5 text-gray-500" />
            </div>
            <div>
              <h4 className="font-bold text-gray-900">Exact City Match</h4>
              <p className="text-sm text-gray-600">Search only in the exact city you specified</p>
            </div>
          </div>
          <button
            type="button"
            onClick={() => onChange({ ...filters, exact_match: !filters.exact_match })}
            className={`relative inline-flex h-7 w-14 items-center rounded-full transition-all duration-300 ${filters.exact_match ? 'bg-green-600 shadow-inner' : 'bg-gray-300'}`}
          >
            <span
              className={`inline-block h-5 w-5 transform rounded-full bg-white transition-all duration-300 shadow-lg ${filters.exact_match ? 'translate-x-8' : 'translate-x-1'}`}
            />
          </button>
        </div>
      </div>

      {/* Quick Search Actions */}
      <div className="space-y-3">
        <div className="flex items-center justify-between">
          <span className="text-sm font-semibold text-gray-800">Quick Searches</span>
          <button
            type="button"
            onClick={onSearch}
            className="text-sm text-blue-600 hover:text-blue-800 font-medium"
          >
            Search Now
          </button>
        </div>
        
        <div className="grid grid-cols-2 gap-3">
          <button
            type="button"
            onClick={() => {
              setCountryInput('Germany');
              setCityInput('Lahore, Pakistan');
              onChange({ ...filters, country: 'Germany', city: 'Lahore' });
            }}
            className="p-3 border border-gray-200 rounded-lg hover:border-blue-300 hover:bg-blue-50 transition-all text-left group"
          >
            <div className="flex items-center gap-2 mb-1">
              <Navigation className="w-3 h-3 text-blue-500" />
              <span className="text-xs font-medium text-gray-500">Popular</span>
            </div>
            <div className="text-sm font-medium text-gray-900">
              🇩🇪 Germany from Lahore
            </div>
          </button>
          
          <button
            type="button"
            onClick={() => {
              setCountryInput('Canada');
              setCityInput('Karachi, Pakistan');
              onChange({ ...filters, country: 'Canada', city: 'Karachi' });
            }}
            className="p-3 border border-gray-200 rounded-lg hover:border-green-300 hover:bg-green-50 transition-all text-left group"
          >
            <div className="flex items-center gap-2 mb-1">
              <Navigation className="w-3 h-3 text-green-500" />
              <span className="text-xs font-medium text-gray-500">Popular</span>
            </div>
            <div className="text-sm font-medium text-gray-900">
              🇨🇦 Canada from Karachi
            </div>
          </button>
        </div>
      </div>

      {/* Selected Filters Preview */}
      {(filters.country || filters.city) && (
        <div className="p-4 bg-gradient-to-r from-blue-50 to-cyan-50 rounded-xl border border-blue-100">
          <h4 className="font-semibold text-blue-800 mb-2">Selected Filters</h4>
          <div className="flex flex-wrap gap-2">
            {filters.country && (
              <span className="px-3 py-1.5 bg-white text-blue-700 text-sm font-medium rounded-lg border border-blue-200 flex items-center gap-2">
                <Globe className="w-3 h-3" />
                {filters.country}
                <button
                  type="button"
                  onClick={clearCountry}
                  className="hover:bg-blue-100 rounded-full p-0.5"
                >
                  <X className="w-3 h-3" />
                </button>
              </span>
            )}
            {filters.city && (
              <span className="px-3 py-1.5 bg-white text-blue-700 text-sm font-medium rounded-lg border border-blue-200 flex items-center gap-2">
                <MapPin className="w-3 h-3" />
                {filters.city} {/* This shows only city name */}
                <button
                  type="button"
                  onClick={clearCity}
                  className="hover:bg-blue-100 rounded-full p-0.5"
                >
                  <X className="w-3 h-3" />
                </button>
              </span>
            )}
            {filters.digital_only && (
              <span className="px-3 py-1.5 bg-white text-blue-700 text-sm font-medium rounded-lg border border-blue-200 flex items-center gap-2">
                <Monitor className="w-3 h-3" />
                Digital Only
              </span>
            )}
            {filters.exact_match && (
              <span className="px-3 py-1.5 bg-white text-green-700 text-sm font-medium rounded-lg border border-green-200 flex items-center gap-2">
                <Target className="w-3 h-3" />
                Exact Match
              </span>
            )}
          </div>
        </div>
      )}

      {/* API Setup Instructions */}
{/*      {!GEOAPIFY_API && (
        <div className="p-4 bg-amber-50 border border-amber-200 rounded-xl">
          <div className="flex items-start gap-3">
            <div className="p-1.5 bg-amber-100 rounded-lg">
              <Shield className="w-4 h-4 text-amber-600" />
            </div>
            <div className="flex-1">
              <p className="text-sm font-medium text-amber-800 mb-1">
                City Search API Not Configured
              </p>
              <p className="text-xs text-amber-600">
                For enhanced city search, add your Geoapify API key to <code className="bg-amber-100 px-1 rounded">NEXT_PUBLIC_GEOAPIFY_API_KEY</code> in .env.local
              </p>
            </div>
          </div>
        </div>
      )}*/}
    </div>
  );
}