import React, { useRef, useState } from 'react';
import { View, StyleSheet, TouchableOpacity, Text } from 'react-native';
import ActionSheet, { SheetManager } from 'react-native-actions-sheet';
import { Colors } from 'src/theme';
import { GOOGLE_MAP_PLACES_APIKEY } from 'src/constants';

import { getFontSize } from 'src/utils';
import SearchIcon from 'assets/icons/search.svg';
import {
  GooglePlaceData,
  GooglePlaceDetail,
  GooglePlacesAutocomplete
} from 'react-native-google-places-autocomplete';
import MapView, { Marker } from 'react-native-maps';
import axios from 'axios';
import { GooglePlacesAutocompleteDefaultProps } from '../../SuggestSeriesScreen/GooglePlacesAutocompleteProps';

const AddMapPinModal = () => {
  const mapRef = useRef<MapView>(null);

  const [data, setData] = useState<any>(null);
  const [marker, setMarker] = useState<any>(null);

  const handleSheetOpen = (payload: any) => {
    setData(payload);
    if (payload?.pin && payload.pin?.coordinate) {
      setMarker(payload.pin);
    }
  };

  const animateMapToRegion = (latitude: number, longitude: number) => {
    const region = {
      latitude,
      longitude,
      latitudeDelta: 0.015,
      longitudeDelta: 0.0121
    };
    mapRef.current?.animateToRegion(region, 500);
  };

  const handlePlaceSelection = (googleData: GooglePlaceData, details: GooglePlaceDetail | null) => {
    if (details) {
      const { geometry, address_components } = details;

      const cityComponent = address_components?.find(
        (component) =>
          component.types.includes('locality') ||
          component.types.includes('administrative_area_level_2')
      );
      const city = cityComponent?.long_name || null;

      setMarker({
        placeId: googleData.place_id,
        name: googleData.structured_formatting.main_text,
        coordinate: {
          latitude: geometry.location.lat,
          longitude: geometry.location.lng
        },
        url: details.url,
        city: city
      });
      animateMapToRegion(geometry.location.lat, geometry.location.lng);
    }
  };

  const findPlace = async (placeId: string) => {
    const response = await axios.get(
      `https://maps.googleapis.com/maps/api/place/details/json?place_id=${placeId}&language=en&fields=address_component,name,url&key=${GOOGLE_MAP_PLACES_APIKEY}`
    );

    const result = response.data.result;
    const addressComponents = result.address_components || [];

    const cityComponent = addressComponents.find(
      (component: { types: string | string[] }) =>
        component.types.includes('locality') ||
        component.types.includes('administrative_area_level_2')
    );

    const city = cityComponent ? cityComponent?.long_name || null : null;

    return { url: result.url, name: result.name, city: city };
  };

  const handlePoiClick = async (event: any) => {
    const { placeId, coordinate } = event.nativeEvent;
    const { url, name, city } = await findPlace(placeId);
    setMarker({
      placeId,
      name,
      coordinate,
      url,
      city
    });
    animateMapToRegion(coordinate.latitude, coordinate.longitude);
  };

  return (
    <ActionSheet
      id="add-map-pin-modal"
      containerStyle={styles.sheetContainer}
      defaultOverlayOpacity={0.5}
      closeOnTouchBackdrop={true}
      keyboardHandlerEnabled={false}
      onBeforeShow={(sheetRef) => {
        const payload = sheetRef || null;
        handleSheetOpen(payload);
      }}
    >
      <View style={styles.container}>
        <View style={styles.header}>
          <TouchableOpacity
            style={{
              paddingTop: 16,
              paddingBottom: 6,
              paddingHorizontal: 6
            }}
            onPress={() => {
              SheetManager.hide('add-map-pin-modal');
            }}
          >
            <Text style={styles.headerText}>Cancel</Text>
          </TouchableOpacity>

          {marker ? (
            <TouchableOpacity
              onPress={() => {
                data?.setPin(marker);
                SheetManager.hide('add-map-pin-modal');
              }}
              style={{
                paddingTop: 16,
                paddingBottom: 6,
                paddingHorizontal: 6
              }}
            >
              <Text style={styles.headerText}>Save</Text>
            </TouchableOpacity>
          ) : null}
        </View>

        <View style={styles.searchContainer}>
          <GooglePlacesAutocomplete
            {...GooglePlacesAutocompleteDefaultProps}
            placeholder="Find a spot"
            onPress={handlePlaceSelection}
            query={{
              key: GOOGLE_MAP_PLACES_APIKEY,
              language: 'en',
              types: 'establishment'
            }}
            GooglePlacesDetailsQuery={{
              language: 'en'
            }}
            nearbyPlacesAPI="GooglePlacesSearch"
            fetchDetails={true}
            styles={{
              textInput: styles.searchInput
            }}
            isRowScrollable={true}
            renderLeftButton={() => (
              <View style={styles.searchIcon}>
                <SearchIcon fill={Colors.LIGHT_GRAY} />
              </View>
            )}
          />
        </View>

        <View style={styles.mapContainer}>
          <MapView
            ref={mapRef}
            style={styles.map}
            showsMyLocationButton={true}
            showsUserLocation={true}
            showsCompass={false}
            zoomControlEnabled={false}
            mapType={'standard'}
            initialRegion={{
              latitude: 0,
              longitude: 0,
              latitudeDelta: 180,
              longitudeDelta: 180
            }}
            provider="google"
            onPoiClick={handlePoiClick}
          >
            {marker && <Marker coordinate={marker.coordinate} />}
          </MapView>
        </View>
      </View>
    </ActionSheet>
  );
};

const styles = StyleSheet.create({
  map: {
    ...StyleSheet.absoluteFillObject
  },
  searchContainer: {
    gap: 16,
    flexDirection: 'row',
    alignItems: 'center'
  },
  searchInput: {
    backgroundColor: Colors.FILL_LIGHT,
    borderRadius: 0,
    borderTopRightRadius: 4,
    borderBottomRightRadius: 4,
    height: 38
  },
  searchIcon: {
    height: 36,
    backgroundColor: Colors.FILL_LIGHT,
    paddingLeft: 16,
    alignItems: 'center',
    justifyContent: 'center',
    borderTopLeftRadius: 4,
    borderBottomLeftRadius: 4
  },
  header: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center'
  },
  headerText: {
    color: Colors.DARK_BLUE,
    fontSize: getFontSize(14),
    fontWeight: '700'
  },
  container: {
    backgroundColor: 'white',
    gap: 16,
    height: '100%'
  },
  mapContainer: {
    flex: 1,
    justifyContent: 'center',
    marginHorizontal: -16,
    overflow: 'hidden'
  },
  sheetContainer: {
    height: '95%',
    borderTopLeftRadius: 15,
    borderTopRightRadius: 15,
    paddingHorizontal: 16,
    overflow: 'hidden'
  }
});

export default AddMapPinModal;
