'use client';

import { useState, useRef, useEffect } from 'react';
import { Sparkles, Mic, Send, Brain, Wand2, Clock, Globe, MapPin, Navigation, Settings, ChevronDown } from 'lucide-react';

interface AISearchBoxProps {
  value: string;
  onChange: (value: string) => void;
  onSearch: (queryWithRadius?: string) => void;
  loading?: boolean;
  selectedRadius: number;
  onRadiusChange: (radius: number) => void;
  includeRadius: boolean;
  onIncludeRadiusChange: (include: boolean) => void;
}

const EXAMPLE_PROMPTS = [
  {
    text: 'I need help with Germany student visa application from Lahore. Need someone who responds quickly.',
    icon: Globe,
    color: 'from-blue-100/80 to-blue-50/80 border-blue-200/60 hover:border-blue-300',
    radius: 100
  },
  {
    text: 'Looking for Canada PR consultant in Delhi with IELTS preparation support and fast response.',
    icon: Clock,
    color: 'from-green-100/80 to-green-50/80 border-green-200/60 hover:border-green-300',
    radius: 50
  },
  {
    text: 'Need urgent help with US work visa from Mumbai. Digital consultation preferred.',
    icon: Wand2,
    color: 'from-purple-100/80 to-purple-50/80 border-purple-200/60 hover:border-purple-300',
    radius: 200
  },
  {
    text: 'Family visa assistance for UK from Karachi, budget under $200, English speaking consultant.',
    icon: Brain,
    color: 'from-amber-100/80 to-amber-50/80 border-amber-200/60 hover:border-amber-300',
    radius: 150
  }
];

export default function AISearchBox({ 
  value, 
  onChange, 
  onSearch, 
  loading,
  selectedRadius,
  onRadiusChange,
  includeRadius,
  onIncludeRadiusChange
}: AISearchBoxProps) {
  const [isListening, setIsListening] = useState(false);
  const [selectedCity, setSelectedCity] = useState<string>('');
  const recognition = useRef<any>(null);
  const textareaRef = useRef<HTMLTextAreaElement>(null);

  useEffect(() => {
    if (typeof window !== 'undefined' && 'webkitSpeechRecognition' in window) {
      const SpeechRecognition = (window as any).webkitSpeechRecognition;
      const recognitionInstance = new SpeechRecognition();
      recognitionInstance.continuous = false;
      recognitionInstance.interimResults = false;
      recognitionInstance.lang = 'en-US';

      recognitionInstance.onstart = () => setIsListening(true);
      recognitionInstance.onend = () => setIsListening(false);
      recognitionInstance.onresult = (event: any) => {
        const transcript = event.results[0][0].transcript;
        onChange(transcript);
        setTimeout(() => handleSearch(transcript), 500);
      };

      recognition.current = recognitionInstance;
    }
  }, [onChange]);

  // Extract city from query
  useEffect(() => {
    if (value) {
      const extractedCity = extractCityFromQuery(value);
      if (extractedCity) {
        setSelectedCity(extractedCity);
        // If city is mentioned, default to radius search if not already set
        if (includeRadius && selectedRadius === 0) {
          onRadiusChange(100);
        }
      }
    }
  }, [value, includeRadius, selectedRadius, onRadiusChange]);

  const extractCityFromQuery = (query: string): string | null => {
    const queryLower = query.toLowerCase();
    const cities = ['Lahore', 'Karachi', 'Islamabad', 'Delhi', 'Dubai', 'London', 'Mumbai', 'Toronto', 'Sydney'];
    
    for (const city of cities) {
      if (queryLower.includes(city.toLowerCase())) {
        return city;
      }
    }
    
    // Try to extract city using patterns
    const cityPatterns = [
      /(?:from|in|near|around)\s+([A-Z][a-zA-Z\s]+?)(?:\.|,|$)/i,
      /([A-Z][a-zA-Z\s]+?)(?:\s+consultant|\s+visa|\s+help)/i
    ];
    
    for (const pattern of cityPatterns) {
      const match = query.match(pattern);
      if (match) {
        const potentialCity = match[1].trim();
        // Check if it's a known city or looks like a city name
        if (potentialCity.length > 2 && !potentialCity.includes('need') && !potentialCity.includes('help')) {
          return potentialCity;
        }
      }
    }
    
    return null;
  };

  const handleVoiceInput = () => {
    if (recognition.current) {
      if (isListening) {
        recognition.current.stop();
      } else {
        recognition.current.start();
      }
    } else {
      alert('Voice recognition is not supported in your browser. Please use Chrome or Edge.');
    }
  };

  const handleSearch = (customQuery?: string) => {
    const searchQuery = customQuery || value.trim();
    if (!searchQuery) return;
    
    // Create enhanced query with radius parameter
    let enhancedQuery = searchQuery;
    
    if (includeRadius && selectedRadius > 0 && selectedCity) {
      // Format: Original query [RADIUS:100km CITY:Lahore]
      enhancedQuery = `${searchQuery} [RADIUS:${selectedRadius}km CITY:${selectedCity}]`;
    } else if (includeRadius && selectedRadius > 0 && !selectedCity) {
      // User wants radius search but no city mentioned - add just radius
      enhancedQuery = `${searchQuery} [RADIUS:${selectedRadius}km]`;
    } else if (!includeRadius && selectedCity) {
      // Exact city only
      enhancedQuery = `${searchQuery} [EXACT_CITY:${selectedCity}]`;
    }
    
    console.log('🔍 Enhanced Query for API:', {
      original: searchQuery,
      enhanced: enhancedQuery,
      radius: selectedRadius,
      includeRadius: includeRadius,
      city: selectedCity
    });
    
    onSearch(enhancedQuery);
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    handleSearch();
  };

  const handleExampleClick = (exampleText: string, exampleRadius: number) => {
    onRadiusChange(exampleRadius);
    onChange(exampleText);
    
    setTimeout(() => {
      if (textareaRef.current) {
        textareaRef.current.focus();
      }
      setTimeout(() => handleSearch(exampleText), 100);
    }, 50);
  };

  const handleRadiusChange = (newRadius: number) => {
    onRadiusChange(newRadius);
  };

  const handleIncludeRadiusChange = (include: boolean) => {
    onIncludeRadiusChange(include);
    // If enabling radius search and radius is 0, set default
    if (include && selectedRadius === 0) {
      onRadiusChange(100);
    }
  };

  useEffect(() => {
    if (textareaRef.current) {
      textareaRef.current.style.height = 'auto';
      textareaRef.current.style.height = `${textareaRef.current.scrollHeight}px`;
    }
  }, [value]);

  return (
    <form onSubmit={handleSubmit} className="space-y-5">
      <div className="relative">
        <div className="absolute -top-3 left-4 z-10">
          <div className="flex items-center gap-2 bg-gradient-to-r from-purple-600/90 to-blue-600/90 text-white px-4 py-1.5 rounded-full text-xs font-semibold shadow-lg backdrop-blur-sm">
            <Brain className="w-3 h-3" />
            <span>AI Assistant</span>
          </div>
        </div>
        
        <textarea
          ref={textareaRef}
          value={value}
          onChange={(e) => onChange(e.target.value)}
          placeholder="Describe your immigration needs... Example: 'I live in Lahore and need help with Germany student visa application. I want fast response and documentation support. My budget is $200.'"
          className="w-full p-4 pl-5 pr-12 border-2 border-gray-300/80 rounded-2xl focus:border-blue-500 focus:ring-3 focus:ring-blue-100/50 resize-none min-h-[120px] transition-all duration-300 text-gray-700 placeholder-gray-400/70 bg-white/95 backdrop-blur-sm"
          disabled={loading}
          rows={3}
          onKeyDown={(e) => {
            if (e.key === 'Enter' && e.ctrlKey) {
              handleSubmit(e);
            }
          }}
        />
        
        <div className="absolute bottom-3 left-5 text-xs text-gray-400/80">
          {value.length > 0 && (
            <span className={value.length > 500 ? 'text-red-500/90' : ''}>
              {value.length}/500
            </span>
          )}
        </div>
        
        <div className="absolute right-3 bottom-3 flex flex-col gap-1.5">
          <button
            type="button"
            onClick={handleVoiceInput}
            disabled={loading}
            className={`p-2 rounded-xl transition-all duration-300 ${
              isListening 
                ? 'bg-red-100 text-red-600 animate-pulse shadow-md' 
                : 'bg-gray-100/80 hover:bg-gray-200 hover:shadow-sm text-gray-600'
            } ${loading ? 'opacity-50 cursor-not-allowed' : ''}`}
            title={isListening ? 'Stop recording' : 'Voice input'}
          >
            <Mic className="w-3.5 h-3.5" />
          </button>
          
          <button
            type="submit"
            disabled={loading || !value.trim()}
            className={`p-2 rounded-xl transition-all duration-300 ${
              value.trim() 
                ? 'bg-gradient-to-r from-[#0B6F78] to-[#0a306b] text-white hover:shadow-md hover:scale-105' 
                : 'bg-gray-100/80 text-gray-400 cursor-not-allowed'
            } ${loading ? 'opacity-50' : ''}`}
            title="Search with AI"
          >
            <Send className="w-3.5 h-3.5" />
          </button>
        </div>
        
        <div className="absolute -bottom-5 right-0 text-xs text-gray-400/70">
          Press Ctrl+Enter to search
        </div>
      </div>

      {/* Radius Selector Section */}
      <div className="bg-gradient-to-r from-blue-50/80 to-indigo-50/80 border border-blue-100/60 rounded-2xl p-4 backdrop-blur-sm shadow-sm">
        <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 mb-3">
          <div className="flex items-center gap-2">
            <div className="p-1.5 bg-white/80 rounded-lg shadow-xs">
              <Navigation className="w-4 h-4 text-blue-600" />
            </div>
            <div>
              <h4 className="font-semibold text-blue-800 text-sm">Search Radius Settings</h4>
              <p className="text-xs text-blue-600/80">
                {selectedCity 
                  ? `Applied to searches ${includeRadius ? `within ${selectedRadius}km` : ``}` 
                  : 'Will apply'}
              </p>
            </div>
          </div>
          
          <div className="flex items-center gap-2">
            <div className="relative">
              <input
                type="checkbox"
                id="includeRadius"
                checked={includeRadius}
                onChange={(e) => handleIncludeRadiusChange(e.target.checked)}
                className="sr-only peer"
              />
              <label 
                htmlFor="includeRadius" 
                className="flex items-center gap-2 text-sm text-gray-700 cursor-pointer"
              >
                <div className="w-5 h-5 rounded border border-gray-300 peer-checked:bg-blue-500 peer-checked:border-blue-500 flex items-center justify-center transition-colors">
                  {includeRadius && <div className="w-2 h-2 bg-white rounded-sm"></div>}
                </div>
                Radius Search
              </label>
            </div>
          </div>
        </div>

        <div className="space-y-3">
          <div className="flex items-center justify-between">
            <span className="text-sm text-gray-600">Search Range:</span>
            <span className="text-sm font-medium text-blue-700">
              {includeRadius ? `${selectedRadius} km radius` : 'Exact city only'}
            </span>
          </div>
          
          <div className="px-1">
            <input
              type="range"
              min="0"
              max="500"
              step="50"
              value={selectedRadius}
              onChange={(e) => handleRadiusChange(parseInt(e.target.value))}
              className="w-full h-2 bg-gradient-to-r from-blue-100 via-cyan-100 to-blue-100 rounded-full appearance-none [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:h-4 [&::-webkit-slider-thumb]:w-4 [&::-webkit-slider-thumb]:rounded-full [&::-webkit-slider-thumb]:bg-gradient-to-r [&::-webkit-slider-thumb]:from-blue-600 [&::-webkit-slider-thumb]:to-cyan-600 [&::-webkit-slider-thumb]:shadow-md"
              disabled={!includeRadius}
            />
          </div>
          
          <div className="flex flex-wrap gap-1.5">
            {[0, 50, 100, 200, 300, 500].map((radius) => (
              <button
                key={radius}
                type="button"
                onClick={() => handleRadiusChange(radius)}
                className={`px-2.5 py-1.5 text-xs font-medium rounded-lg transition-all flex-1 min-w-[60px] ${
                  selectedRadius === radius
                    ? radius === 0
                      ? 'bg-gray-600 text-white shadow-sm'
                      : 'bg-gradient-to-r from-blue-600 to-cyan-600 text-white shadow-sm'
                    : 'bg-white/80 text-blue-700 border border-blue-200/50 hover:bg-blue-50/80'
                } ${!includeRadius && radius > 0 ? 'opacity-50 cursor-not-allowed' : ''}`}
                disabled={!includeRadius && radius > 0}
              >
                {radius === 0 ? 'Exact City' : `${radius}km`}
              </button>
            ))}
          </div>
          
          <div className="pt-2 border-t border-blue-100/50">
            <p className="text-xs text-gray-600">
              <span className="font-medium text-blue-600">Current setting:</span> {
                includeRadius 
                  ? `Your searches will include consultants within ${selectedRadius}km radius of mentioned cities`
                  : 'Your searches will be limited to exact cities only'
              }
            </p>
            {selectedCity && !includeRadius && (
              <p className="text-xs text-green-600 mt-1">
                ✓ Next search will be limited to {selectedCity} only
              </p>
            )}
          </div>
        </div>
      </div>

      {/* Example prompts */}
      <div className="space-y-3">
        <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2">
          <div className="flex items-center gap-2">
            <div className="p-1 bg-gradient-to-r from-purple-500/10 to-blue-500/10 rounded">
              <Sparkles className="w-3.5 h-3.5 text-purple-500" />
            </div>
            <span className="text-sm font-medium text-gray-700">Quick Examples</span>
          </div>
          <button
            type="button"
            onClick={() => {
              onChange('');
              setSelectedCity('');
            }}
            className="text-xs text-blue-600 hover:text-blue-800 font-medium hover:underline transition-colors px-3 py-1.5 bg-white/60 hover:bg-white rounded-lg"
          >
            Clear input
          </button>
        </div>
        
        <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
          {EXAMPLE_PROMPTS.map((example, idx) => {
            const Icon = example.icon;
            return (
              <button
                key={idx}
                type="button"
                onClick={() => handleExampleClick(example.text, example.radius)}
                disabled={loading}
                className={`text-left p-3 rounded-xl border hover:shadow-md transition-all duration-300 bg-gradient-to-r ${example.color} hover:-translate-y-0.5 disabled:opacity-50 disabled:cursor-not-allowed group backdrop-blur-sm`}
              >
                <div className="flex items-start gap-2.5">
                  <div className="p-1.5 bg-white/80 rounded-lg shadow-xs group-hover:scale-110 transition-transform">
                    <Icon className="w-3.5 h-3.5 text-blue-600" />
                  </div>
                  <div className="flex-1 min-w-0">
                    <p className="text-xs text-gray-700 font-medium leading-tight line-clamp-2">
                      {example.text}
                    </p>
                  </div>
                </div>
                <div className="mt-2 flex items-center justify-between">
                  <div className="text-xs text-gray-500/80 flex items-center gap-1">
                    <span>Click to try</span>
                    <Send className="w-2.5 h-2.5" />
                  </div>
                  <div className="flex items-center gap-1.5">
                    <div className="px-1.5 py-0.5 bg-blue-500/10 text-blue-600 text-[10px] font-medium rounded">
                      {example.radius}km radius
                    </div>
                    <ChevronDown className="w-3 h-3 text-blue-400 group-hover:translate-y-0.5 transition-transform" />
                  </div>
                </div>
              </button>
            );
          })}
        </div>
      </div>
      
      {/* Tips */}
      <div className="bg-gradient-to-r from-blue-50/80 to-cyan-50/80 border border-blue-100/60 rounded-xl p-3 backdrop-blur-sm">
        <div className="flex items-start gap-2.5">
          <div className="p-1.5 bg-gradient-to-r from-blue-500/10 to-cyan-500/10 rounded-lg">
            <Brain className="w-3.5 h-3.5 text-blue-600" />
          </div>
          <div className="flex-1">
            <p className="text-xs font-medium text-blue-800 mb-1.5">How Radius Search Works</p>
            <div className="grid grid-cols-1 xs:grid-cols-2 gap-1.5">
              <div className="flex items-start gap-1.5">
                <div className="w-1.5 h-1.5 bg-blue-400 rounded-full mt-1 flex-shrink-0"></div>
                <span className="text-xs text-blue-600/90 leading-tight">
                  AI analyzes your query and extracts city/location
                </span>
              </div>
              <div className="flex items-start gap-1.5">
                <div className="w-1.5 h-1.5 bg-blue-400 rounded-full mt-1 flex-shrink-0"></div>
                <span className="text-xs text-blue-600/90 leading-tight">
                  Finds all nearby cities within selected radius
                </span>
              </div>
              <div className="flex items-start gap-1.5">
                <div className="w-1.5 h-1.5 bg-blue-400 rounded-full mt-1 flex-shrink-0"></div>
                <span className="text-xs text-blue-600/90 leading-tight">
                  Searches consultants from primary + nearby cities
                </span>
              </div>
              <div className="flex items-start gap-1.5">
                <div className="w-1.5 h-1.5 bg-blue-400 rounded-full mt-1 flex-shrink-0"></div>
                <span className="text-xs text-blue-600/90 leading-tight">
                  Groups results by city for easy comparison
                </span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </form>
  );
}