import {StyleSheet, View, Text, Image} from 'react-native';
import Mapbox, {MarkerView} from '@rnmapbox/maps';

import React, {useState} from 'react'; // Add useState import

import DisplayMarkerList from '@components/map/DisplayMarkerList';

import getLocationData from '@components/map/cluster/getData';
import {PA_Point} from '@components/map/types';
import {store} from '@redux/store';
import {appNonSaveVarActions} from '@configs/appNonSaveVarReducer';
import {Position} from '@rnmapbox/maps/src/types/Position';

import {Dimensions} from 'react-native';

Mapbox.setAccessToken(
  'pk.eyJ1IjoidGl0YW5pdW1iYWNoIiwiYSI6ImNscGgzZGJxMDAwbHQyaXA2N3BtOWUxbWkifQ.x-f8JJxwQHWmPFI3P6Qn-w',
);

let lastCameraChange = 0;
let isRerenderData = 0;

export const Map = () => {
  const mapRef = React.useRef<Mapbox.MapView | null>(null);
  //const [mapMarkers, setMapMarkers] = useState<PA_Point[]>([]); // Add useState for visibleBounds
  const [lastDataRerender, setLastDataRerender] = useState(0); // Add useState for visibleBounds

  const getVisibleBounds = async () => {
    // return when lastDataRerender is 300ms ago
    const now = Date.now();

    if (now - lastDataRerender < 2000) return;

    isRerenderData = now;

    //console.log('----1');

    if (mapRef.current) {
      const visibleBounds = await (
        mapRef.current as Mapbox.MapView
      ).getVisibleBounds();

      /*  const deviceWidth = Dimensions.get('window').width;
      const deviceHeight = Dimensions.get('window').height;

      const visibleBounds: [Position, Position] = [
        await mapRef.current.getCoordinateFromView([100, 100]),
        await mapRef.current.getCoordinateFromView([100, 200]),
      ];

      //log visibleBounds
      console.log(visibleBounds);
      */

      //const zoomLevel = await (mapRef.current as Mapbox.MapView).getZoom();

      //console.log('----2', Date.now() - now + 'ms');

      //console.log(visibleBounds);
      let markerData = (await getLocationData(visibleBounds, 0))?.locations;

      //console.log('----3', Date.now() - now + 'ms');

      store.dispatch(appNonSaveVarActions.setMapMarkers(markerData || []));
      //setMapMarkers(markerData || []);

      //console.log('----4', Date.now() - now + 'ms');
    }

    isRerenderData = 0;
  };

  function onCameraChanged() {
    const now = Date.now();

    if (now - lastCameraChange > 500) {
      lastCameraChange = now;
      setTimeout(getVisibleBounds, 500);
      //console.log('------------5', Date.now() - now + 'ms');
    }
  }

  function onMapMoveFinished() {
    //console.log('xxxxxxxxxxxxxxxxxxxdad');

    (async () => {
      await getVisibleBounds();
    })();
  }

  React.useEffect(() => {
    let intervalId: NodeJS.Timeout;

    if (mapRef.current !== null) {
    }

    const executeInterval = async () => {
      await getVisibleBounds();
      intervalId = setTimeout(executeInterval, 50000);
    };

    executeInterval();

    return () => {
      clearInterval(intervalId);
    };
  }, []);

  return (
    <View style={styles.page}>
      <View style={styles.container}>
        <Mapbox.MapView
          ref={mapRef}
          onMapIdle={onMapMoveFinished}
          onCameraChanged={onCameraChanged}
          style={styles.map}
          compassEnabled={true}
          scaleBarEnabled={false}
          //attributionPosition={{bottom: 75, left: 100}}
          //logoPosition={{bottom: 75, left: 10}}
          attributionPosition={{top: 10, left: 100}}
          logoPosition={{top: 10, left: 10}}
          styleURL="mapbox://styles/titaniumbach/clpij5uoo00o301pg2dj23j0m"
          projection="globe">
          <DisplayMarkerList />
        </Mapbox.MapView>
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  page: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  container: {
    height: '100%',
    width: '100%',
  },
  map: {
    flex: 1,
  },
});
