import React, { useState } from 'react';
import { View } from 'react-native';
import * as Location from 'expo-location';
import { tw, MyText, MyTouchableOpacity } from 'common-ui';

interface LocationAttacherProps {
  onLocationChange?: (location: { latitude: number; longitude: number } | null) => void;
  initialLocation?: { latitude: number; longitude: number };
  initialGoogleMapsUrl?: string;
  showGoogleMapsOption?: boolean;
  googleMapsUrl?: string;
  onGoogleMapsUrlChange?: (url: string) => void;
  disabled?: boolean;
  containerStyle?: any;
  attachButtonText?: string;
  googleMapsButtonText?: string;
}

export const LocationAttacher: React.FC<LocationAttacherProps> = ({
  onLocationChange,
  initialLocation,
  initialGoogleMapsUrl = '',
  showGoogleMapsOption = true,
  googleMapsUrl: controlledGoogleMapsUrl,
  onGoogleMapsUrlChange,
  disabled = false,
  containerStyle,
  attachButtonText = 'Attach Current Location',
  googleMapsButtonText = 'Attach with Google Maps',
}) => {
  const [locationLoading, setLocationLoading] = useState(false);
  const [locationError, setLocationError] = useState<string | null>(null);
  const [locationSuccess, setLocationSuccess] = useState(false);
  const [currentLocation, setCurrentLocation] = useState<{ latitude: number; longitude: number } | null>(
    initialLocation || null
  );
  const [showGoogleMapsField, setShowGoogleMapsField] = useState(!!initialGoogleMapsUrl);
  const [internalGoogleMapsUrl, setInternalGoogleMapsUrl] = useState(initialGoogleMapsUrl);

  // Use controlled or uncontrolled Google Maps URL
  const googleMapsUrl = controlledGoogleMapsUrl !== undefined ? controlledGoogleMapsUrl : internalGoogleMapsUrl;
  
  const handleGoogleMapsUrlChange = (url: string) => {
    if (onGoogleMapsUrlChange) {
      onGoogleMapsUrlChange(url);
    } else {
      setInternalGoogleMapsUrl(url);
    }
  };

  const attachCurrentLocation = async () => {
    if (disabled) return;
    
    setLocationLoading(true);
    setLocationError(null);
    setLocationSuccess(false);

    try {
      const { status } = await Location.requestForegroundPermissionsAsync();

      if (status !== 'granted') {
        setLocationError('Location Permission denied');
        return;
      }

      const location = await Location.getCurrentPositionAsync({
        accuracy: Location.Accuracy.High,
      });

      const { latitude, longitude } = location.coords;
      const newLocation = { latitude, longitude };
      setCurrentLocation(newLocation);
      setLocationSuccess(true);
      onLocationChange?.(newLocation);
      // Clear success message after 3 seconds
      setTimeout(() => setLocationSuccess(false), 3000);
    } catch (error) {
      setLocationError('Unable to fetch location. Please check your GPS settings.');
    } finally {
      setLocationLoading(false);
    }
  };

  return (
    <View style={containerStyle}>
      {/* Location Status */}
      {locationLoading ? (
        <MyText style={tw`text-blue-500 text-sm mb-2`}>Fetching location...</MyText>
      ) : locationError ? (
        <MyText style={tw`text-red-500 text-sm mb-2`}>{locationError}</MyText>
      ) : locationSuccess ? (
        <View style={tw`flex-row items-center mb-4`}>
          <View style={tw`bg-green-100 px-3 py-1 rounded-full`}>
            <MyText style={tw`text-green-600 text-sm font-medium`}>✓ Location Attached</MyText>
          </View>
          <MyTouchableOpacity
            onPress={() => attachCurrentLocation()}
            disabled={locationLoading || disabled}
            style={tw`ml-4`}
          >
            <MyText style={tw`text-blue-500 text-sm font-medium`}>Attach Current</MyText>
          </MyTouchableOpacity>
        </View>
      ) : currentLocation ? (
        <View style={tw`flex-row items-center mb-4`}>
          <View style={tw`bg-green-100 px-3 py-1 rounded-full`}>
            <MyText style={tw`text-green-600 text-sm font-medium`}>✓ Location Attached</MyText>
          </View>
          <MyTouchableOpacity
            onPress={() => attachCurrentLocation()}
            disabled={locationLoading || disabled}
            style={tw`ml-4`}
          >
            <MyText style={tw`text-blue-500 text-sm font-medium`}>Attach Current</MyText>
          </MyTouchableOpacity>
        </View>
      ) : (
        <MyTouchableOpacity
          onPress={() => attachCurrentLocation()}
          disabled={locationLoading || disabled}
          style={tw`mb-4`}
        >
          <MyText style={tw`text-blue-500 text-sm font-medium`}>
            {attachButtonText}
          </MyText>
        </MyTouchableOpacity>
      )}

      {/* Google Maps Option - Only show button if not in controlled mode */}
      {showGoogleMapsOption && onGoogleMapsUrlChange === undefined && (
        <>
          <MyTouchableOpacity
            onPress={() => setShowGoogleMapsField(true)}
            disabled={disabled}
            style={tw`mb-1`}
          >
            <MyText style={tw`text-blue-500 text-sm font-medium`}>
              {googleMapsButtonText}
            </MyText>
          </MyTouchableOpacity>

          {showGoogleMapsField && (
            <View style={tw`mb-2`}>
              <MyText style={tw`text-gray-500 text-xs mb-2`}>
                1. Open Google Maps and Find location{'\n'}
                2. Long press the desired location{'\n'}
                3. Click on Share and Click on Copy{'\n'}
                4. Paste the copied url here in the field.
              </MyText>
            </View>
          )}
        </>
      )}
    </View>
  );
};

export default LocationAttacher;
