import YaMap from '../../bare';
import type { YaMapProps } from '../../bare';
import React, { useCallback, useRef } from 'react';
import type { PropsWithChildren } from 'react';
import { useMapViewModel } from '../domain/map.view-model';
import type { NativeSyntheticEvent } from 'react-native';
import { StyleSheet, View } from 'react-native';
import { withFastCompare } from '../../utils';
import type { CamPos, Point } from '../utils/types';

export type MapProps = YaMapProps & {
  showUserPosition?: boolean; //default: true
  CenterComponent?: React.ComponentType;
  followUserMode?: boolean;
  freezedMode?: boolean;
  nightMode?: boolean; //default: false
  showCenterMarker?: boolean;
  onCameraPositionChanged?: (pos: CamPos) => void;
  onMapLongPress?: (point: Point) => void;
  isZoomGestureCentered?: boolean;
};

export const Map = withFastCompare(
  ({ CenterComponent, ...props }: PropsWithChildren<MapProps>) => {
    const { isVisible, mapRef, listeners } = useMapViewModel();

    const _isFirstTouch = useRef(true);

    const _onCameraPositionChange = useCallback(() => {
      if (_isFirstTouch.current) {
        _isFirstTouch.current = false;
        listeners.onCameraPositionChange();
      }
      // eslint-disable-next-line
  }, [listeners.onCameraPositionChange]);

    const _onCameraPositionChanged = useCallback(
      (pos: NativeSyntheticEvent<CamPos>) => {
        _isFirstTouch.current = true;
        props.onCameraPositionChanged?.(pos.nativeEvent);
        listeners.onCameraPositionChanged(pos.nativeEvent);
      },
      // eslint-disable-next-line
    [props.onCameraPositionChanged, listeners.onCameraPositionChanged]
    );

    const _onMapLongPress = useCallback(
      (p: NativeSyntheticEvent<Point>) => {
        props.onMapLongPress?.(p.nativeEvent);
        listeners.onMapLongPress(p.nativeEvent);
      },
      // eslint-disable-next-line
    [props.onMapLongPress, listeners.onMapLongPress]
    );

    return isVisible ? (
      <React.Fragment>
        <YaMap
          {...props}
          ref={mapRef}
          style={props.style ?? styles.fill}
          rotateGesturesEnabled={false}
          onCameraPositionChange={_onCameraPositionChange}
          onMapLongPress={_onMapLongPress}
          onCameraPositionChangeEnd={_onCameraPositionChanged}
        >
          {props.children}
        </YaMap>
        {!!props.showCenterMarker && (
          <View style={styles.centerPointer}>
            {!!CenterComponent && <CenterComponent />}
          </View>
        )}
      </React.Fragment>
    ) : null;
  }
);

const styles = StyleSheet.create({
  fill: {
    flex: 1,
  },
  centerPointer: {
    width: 50,
    height: 50,
    position: 'absolute',
    top: '50%',
    left: '50%',
    transform: [{ translateX: -25 }, { translateY: -25 }],
  },
});
