import React, {
  useImperativeHandle,
  useEffect,
  useRef,
  forwardRef,
} from 'react';
import {
  SafeAreaView,
  findNodeHandle,
  // PixelRatio,
  DeviceEventEmitter,
  NativeEventEmitter,
  Platform,
  PixelRatio,
} from 'react-native';
import type {
  MAP_EVENT_LISTENER,
  MAP_VIEW_REFERENCE,
  ODP_EVENT_LISTENER,
} from './CommandTypes';
import type {
  MAP_CREDENTIALS,
} from './JibestreamTypes';
import { MapViewManager, CTPEventEmitter } from './MapViewManager';
import {
  centerMap,
  createFragment,
  setMapVenue,
  setUserPosition,
} from './SendCommand';

const MapView = (
  props: {
    style: { height: number; width: number };
    onMapMessage: MAP_EVENT_LISTENER;
    onOdpEvent: ODP_EVENT_LISTENER;
  },
  parentRef: React.Ref<unknown> | undefined
) => {
  const nodeRef = useRef(null);

  useEffect(() => {
    if(Platform.OS == 'android'){
        createFragment(findNodeHandle(nodeRef.current));
    }
  }, []);

  useImperativeHandle(parentRef, () => {
    const viewId = findNodeHandle(nodeRef.current);
    const listeners: MAP_VIEW_REFERENCE = {
        setMapVenue: (credentials: MAP_CREDENTIALS) => {
            setTimeout(function(){
                setMapVenue({
                  viewId,
                  credentials,
                });
            }, 500)
        },
        // setMapVenue: ({
        //   credentials,
        //   compass,
        //   floorSelector,
        //   zoomButtons,
        //   search,
        // }: {
        //   credentials: MAP_CREDENTIALS;
        //   compass?: MAP_COMPASS_PROPERTIES;
        //   floorSelector?: MAP_FLOOR_SELECTOR_PROPERTIES;
        //   zoomButtons?: MAP_ZOOM_BUTTON_PROPERTIES;
        //   search?: MAP_SEARCH_PROPERTIES;
        // }) => {
        //   setMapVenue({
        //     viewId,
        //     credentials,
        //     compass,
        //     floorSelector,
        //     zoomButtons,
        //     search,
        //   });
        // },
      centerMapOnUser: (orientation: number, animationDuration: number = 1000) => {
        centerMap(viewId, orientation, animationDuration);
      },
    //   setFollowBlueDot: (
    //     enabled: boolean,
    //     rotate: boolean = false,
    //     interval: number = 500
    //   ) => {
    //     setFollowBlueDot(viewId, enabled, rotate, interval);
    //   },
      setUserPosition: (lat: number, long: number, heading: number) => {
        setUserPosition(viewId, lat, long, heading);
      },
    //   setUserPositionXY: (x: number, y: number, heading: number) => {
    //     setUserPosition(viewId, x, y, heading, 'xy');
    //   },
    //   clearWayfindingPath: () => {
    //     clearWayfindingPath(viewId);
    //   },
    //   wayfindToWaypoint: (waypointId: number) => {
    //     wayfindToWaypoint(viewId, waypointId);
    //   },
    //   wayfindBetweenWaypoints: (originId: number, destinationId: number) => {
    //     wayfindBetweenWaypoints(viewId, originId, destinationId);
    //   },
    //   drawNavigationPath: (
    //     pathId: string,
    //     shouldFocus: boolean = true,
    //     style: JIBESTREAM_STYLE = {
    //       stroke: '#ffc956',
    //       strokeWidth: 3,
    //     }
    //   ) => {
    //     drawNavigationPath(viewId, pathId, shouldFocus, style);
    //   },
    //   styleUnitsForDestination: (
    //     destination: JIBESTREAM_DESTINATION,
    //     style: JIBESTREAM_STYLE = { fill: '#ABABAB' }
    //   ) => {
    //     styleUnitsForDestination(viewId, destination, style);
    //   },
    //   styleShape: (
    //     unitId: number,
    //     style: JIBESTREAM_STYLE = { fill: '#ABABAB' }
    //   ) => {
    //     styleShape(viewId, unitId, style);
    //   },
    };
    return listeners;
  });

  useEffect(() => {
    console.log('Initializing Event Emitter');
    let eventEmitter: typeof DeviceEventEmitter | NativeEventEmitter | null =
      null;
    if (Platform.OS == 'android') {
      eventEmitter = DeviceEventEmitter;
    } else if (Platform.OS == 'ios') {
      console.log(CTPEventEmitter);
        eventEmitter = new NativeEventEmitter(CTPEventEmitter);
    }
    // eventEmitter?.addListener(
    //   'DESTINATION_SELECTED',
    //   (data: JIBESTREAM_DESTINATION) =>
    //     props.onMapMessage.onDestinationSelected?.(data)
    // );
    // eventEmitter?.addListener(
    //   'NAVIGATION_PATH_GENERATED',
    //   (data: {
    //     pathId: string;
    //     instructions: INSTRUCTION[];
    //     start: JIBESTREAM_WAYPOINT;
    //     end: JIBESTREAM_WAYPOINT;
    //     path: JIBESTREAM_PATH[];
    //   }) =>
    //     props.onMapMessage.onNavigationPathGenerated?.(
    //       data.pathId,
    //       data.instructions,
    //       data.start,
    //       data.end,
    //       data.path
    //     )
    // );
    eventEmitter?.addListener('USER_POSITION_UPDATED', (data: any) =>
      props.onMapMessage.onUserPositionUpdated?.(data)
    );
    // eventEmitter?.addListener('WINDOW_LOADED', () =>
    //   props.onMapMessage.onWindowLoaded?.()
    // );
    // eventEmitter?.addListener('MAP_TAPPED_GENERIC', (data: MAP_TAP_EVENT) =>
    //   props.onMapMessage.onMapTappedGeneric?.(data)
    // );
    // eventEmitter?.addListener('ODP_READY', (event: ODP_ON_READY) => {
    //   console.log('ODP onReady');
    //   props.onOdpEvent.onReady?.(event);
    // });
    // eventEmitter?.addListener(
    //   'ODP_KEY_VALIDATION',
    //   (event: ODP_ON_KEY_VALIDATION) => {
    //     console.log('ODP onKeyValidation');
    //     props.onOdpEvent.onKeyValidation?.(event);
    //   }
    // );
    // eventEmitter?.addListener(
    //   'ODP_NAVIGATION_UPDATE',
    //   (event: ODP_ON_NAVIGATION_UPDATE) => {
    //     props.onOdpEvent.onNavigationUpdate?.(event);
    //   }
    // );
    // eventEmitter?.addListener(
    //   'ODP_FACILITY_UPDATE',
    //   (event: ODP_ON_FACILITY_UPDATE) => {
    //     console.log('ODP onFacilityUpdate');
    //     props.onOdpEvent.onFacilityUpdate?.(event);
    //   }
    // );
    return () => {
      console.log('Removing Event Emitters');
    //   eventEmitter?.removeAllListeners('DESTINATION_SELECTED');
    //   eventEmitter?.removeAllListeners('NAVIGATION_PATH_GENERATED');
      eventEmitter?.removeAllListeners('USER_POSITION_UPDATED');
    //   eventEmitter?.removeAllListeners('WINDOW_LOADED');
    //   eventEmitter?.removeAllListeners('MAP_TAPPED_GENERIC');
    //   eventEmitter?.removeAllListeners('ODP_READY');
    //   eventEmitter?.removeAllListeners('ODP_KEY_VALIDATION');
    //   eventEmitter?.removeAllListeners('ODP_NAVIGATION_UPDATE');
    //   eventEmitter?.removeAllListeners('ODP_FACILITY_UPDATE');
    };
  }, []);


  return (
    <SafeAreaView style={{ flex: 1, width: '100%', height: '100%' }}>
      {MapViewManager ? (
        <MapViewManager
          style={
            
    Platform.OS == 'android' ? {
        // converts dpi to px, provide desired height
        height: PixelRatio.getPixelSizeForLayoutSize(props.style.height),
        // converts dpi to px, provide desired width
        width: PixelRatio.getPixelSizeForLayoutSize(props.style.width),
      } : {

            height: props.style.height / 1,
            width: props.style.width /1
            // converts dpi to px, provide desired height
            // height: PixelRatio.getPixelSizeForLayoutSize(props.style.height),
            // converts dpi to px, provide desired width
            // width: PixelRatio.getPixelSizeForLayoutSize(props.style.width),
          }}
          ref={nodeRef}
        />
      ) : null}
    </SafeAreaView>
  );
};

export default forwardRef(MapView);
