import React, { useState, useEffect } from 'react';
import { geolocationService, LocationData } from '../lib/geolocation';

interface LocationInputProps {
  onLocationChange: (location: LocationData | null) => void;
  initialLocation?: LocationData | null;
  showRadius?: boolean;
  defaultRadius?: number;
  onRadiusChange?: (radius: number) => void;
  className?: string;
}

const LocationInput: React.FC<LocationInputProps> = ({
  onLocationChange,
  initialLocation = null,
  showRadius = true,
  defaultRadius = 50,
  onRadiusChange,
  className = ''
}) => {
  const [location, setLocation] = useState<LocationData | null>(initialLocation);
  const [radius, setRadius] = useState(defaultRadius);
  const [addressInput, setAddressInput] = useState('');
  const [isLoadingGPS, setIsLoadingGPS] = useState(false);
  const [isLoadingAddress, setIsLoadingAddress] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [showAdvanced, setShowAdvanced] = useState(false);

  useEffect(() => {
    if (initialLocation) {
      setLocation(initialLocation);
    }
  }, [initialLocation]);

  const handleGPSLocation = async () => {
    setIsLoadingGPS(true);
    setError(null);

    try {
      const gpsLocation = await geolocationService.getCurrentLocation();
      if (gpsLocation) {
        setLocation(gpsLocation);
        onLocationChange(gpsLocation);
        setAddressInput(''); // Clear address input when GPS is used
      } else {
        // Fallback to IP geolocation
        const ipLocation = await geolocationService.getLocationFromIP();
        if (ipLocation) {
          setLocation(ipLocation);
          onLocationChange(ipLocation);
          setError('GPS not available, using approximate location');
        } else {
          setError('Unable to determine your location');
        }
      }
    } catch (err) {
      setError('Error getting location: ' + (err as Error).message);
    } finally {
      setIsLoadingGPS(false);
    }
  };

  const handleAddressSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!addressInput.trim()) return;

    setIsLoadingAddress(true);
    setError(null);

    try {
      const geocodedLocation = await geolocationService.geocodeAddress(addressInput);
      if (geocodedLocation) {
        setLocation(geocodedLocation);
        onLocationChange(geocodedLocation);
      } else {
        setError('Unable to find that address');
      }
    } catch (err) {
      setError('Error geocoding address: ' + (err as Error).message);
    } finally {
      setIsLoadingAddress(false);
    }
  };

  const handleRadiusChange = (newRadius: number) => {
    setRadius(newRadius);
    if (onRadiusChange) {
      onRadiusChange(newRadius);
    }
  };

  const clearLocation = () => {
    setLocation(null);
    setAddressInput('');
    onLocationChange(null);
    geolocationService.clearCurrentLocation();
  };

  const formatLocationDisplay = (loc: LocationData) => {
    if (loc.city && loc.state) {
      return `${loc.city}, ${loc.state}`;
    }
    return `${loc.latitude.toFixed(4)}, ${loc.longitude.toFixed(4)}`;
  };

  return (
    <div className={`space-y-4 ${className}`}>
      {/* Current Location Display */}
      {location && (
        <div className="bg-green-50 border border-green-200 rounded-lg p-4">
          <div className="flex items-center justify-between">
            <div>
              <div className="flex items-center space-x-2">
                <svg className="h-5 w-5 text-green-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z" />
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 11a3 3 0 11-6 0 3 3 0 016 0z" />
                </svg>
                <span className="text-sm font-medium text-green-800">
                  Current Location
                </span>
              </div>
              <p className="text-sm text-green-700 mt-1">
                {formatLocationDisplay(location)}
              </p>
              {location.source && (
                <p className="text-xs text-green-600 mt-1">
                  Source: {location.source === 'gps' ? 'GPS' : location.source === 'ip_geolocation' ? 'IP Location' : 'Manual'}
                </p>
              )}
            </div>
            <button
              onClick={clearLocation}
              className="text-green-600 hover:text-green-800 text-sm font-medium"
            >
              Clear
            </button>
          </div>
        </div>
      )}

      {/* Location Input Methods */}
      {!location && (
        <div className="space-y-3">
          {/* GPS Location Button */}
          <button
            onClick={handleGPSLocation}
            disabled={isLoadingGPS}
            className="w-full flex items-center justify-center space-x-2 bg-blue-600 text-white py-3 px-4 rounded-lg hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed"
          >
            {isLoadingGPS ? (
              <div className="animate-spin rounded-full h-5 w-5 border-b-2 border-white"></div>
            ) : (
              <svg className="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z" />
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 11a3 3 0 11-6 0 3 3 0 016 0z" />
              </svg>
            )}
            <span>
              {isLoadingGPS ? 'Getting location...' : 'Use My Location'}
            </span>
          </button>

          {/* Address Input */}
          <div>
            <div className="text-center text-sm text-gray-500 mb-3">
              or enter your location
            </div>
            <form onSubmit={handleAddressSubmit} className="space-y-2">
              <div className="flex space-x-2">
                <input
                  type="text"
                  value={addressInput}
                  onChange={(e) => setAddressInput(e.target.value)}
                  placeholder="Enter city, state, or ZIP code"
                  className="flex-1 px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                  disabled={isLoadingAddress}
                />
                <button
                  type="submit"
                  disabled={!addressInput.trim() || isLoadingAddress}
                  className="px-4 py-2 bg-gray-600 text-white rounded-lg hover:bg-gray-700 disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  {isLoadingAddress ? (
                    <div className="animate-spin rounded-full h-5 w-5 border-b-2 border-white"></div>
                  ) : (
                    'Find'
                  )}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* Radius Selector */}
      {showRadius && location && (
        <div className="bg-gray-50 border border-gray-200 rounded-lg p-4">
          <label className="block text-sm font-medium text-gray-700 mb-2">
            Search Radius: {radius} miles
          </label>
          <input
            type="range"
            min="5"
            max="100"
            step="5"
            value={radius}
            onChange={(e) => handleRadiusChange(Number(e.target.value))}
            className="w-full h-2 bg-gray-200 rounded-lg appearance-none cursor-pointer"
          />
          <div className="flex justify-between text-xs text-gray-500 mt-1">
            <span>5 mi</span>
            <span>50 mi</span>
            <span>100 mi</span>
          </div>
        </div>
      )}

      {/* Advanced Options */}
      {location && (
        <div className="space-y-3">
          <button
            onClick={() => setShowAdvanced(!showAdvanced)}
            className="text-sm text-gray-600 hover:text-gray-800 flex items-center space-x-1"
          >
            <span>Advanced Options</span>
            <svg 
              className={`h-4 w-4 transform transition-transform ${showAdvanced ? 'rotate-180' : ''}`}
              fill="none" 
              viewBox="0 0 24 24" 
              stroke="currentColor"
            >
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
            </svg>
          </button>
          
          {showAdvanced && (
            <div className="bg-gray-50 border border-gray-200 rounded-lg p-4 space-y-3">
              <div className="text-sm">
                <div className="font-medium text-gray-700 mb-2">Coordinates</div>
                <div className="text-gray-600">
                  Latitude: {location.latitude.toFixed(6)}<br />
                  Longitude: {location.longitude.toFixed(6)}
                </div>
              </div>
              
              {location.accuracy && (
                <div className="text-sm">
                  <div className="font-medium text-gray-700 mb-1">Accuracy</div>
                  <div className="text-gray-600">
                    ±{location.accuracy.toFixed(0)} meters
                  </div>
                </div>
              )}
              
              <button
                onClick={clearLocation}
                className="text-sm text-red-600 hover:text-red-800 font-medium"
              >
                Reset Location
              </button>
            </div>
          )}
        </div>
      )}

      {/* Error Display */}
      {error && (
        <div className="bg-red-50 border border-red-200 rounded-lg p-4">
          <div className="flex items-center space-x-2">
            <svg className="h-5 w-5 text-red-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.732 16.5c-.77.833.192 2.5 1.732 2.5z" />
            </svg>
            <span className="text-sm text-red-800">{error}</span>
          </div>
        </div>
      )}

      {/* Helper Text */}
      {!location && !error && (
        <div className="text-xs text-gray-500 text-center">
          We'll show you events near your location. Your location data is only used for this search and is not stored.
        </div>
      )}
    </div>
  );
};

export default LocationInput;