import { BackHandler, StyleSheet, View } from 'react-native';
import { HeaderBackProps } from '../types';
import React, { useCallback, useContext, useEffect } from 'react';
import { ApplicationContext, MiniAppContext } from '../../Context';
import { PopupNotify } from '../../Popup';
import { NavigationButton } from './NavigationButton';

/**
 * default header left used for nav
 */
const HeaderLeft: React.FC<HeaderBackProps> = ({
  tintColor,
  preventBack,
  onPressLeftHeader,
  onBackHandler,
}) => {
  const context = useContext<any>(MiniAppContext);
  const { navigator } = useContext(ApplicationContext);

  const goBack = useCallback(() => {
    const canGoBack = navigator?.ref?.current?.canGoBack?.();
    const currentRoute = navigator?.ref?.current?.getCurrentRoute?.();
    context?.autoTracking?.({
      ...context,
      componentName: 'IconButton',
      componentId: 'navigation_back',
      screenName: currentRoute?.params?.screen?.name ?? currentRoute?.name,
    });

    if (canGoBack) {
      navigator?.ref?.current?.goBack?.();
    } else if (navigator?.maxApi) {
      navigator?.maxApi?.dismiss?.(navigator?.dismissData);
    } else {
      (globalThis as any)?.miniAppApi?.dispatch?.('dismiss', context);
    }
  }, [navigator, context]);

  const goBackSafe = useCallback(() => {
    if (preventBack) {
      navigator?.showModal({
        screen: () => (
          <PopupNotify
            {...preventBack}
            primary={{
              title: preventBack.primary.title,
              onPress: () => {
                preventBack?.primary.onPress();
                goBack();
              },
            }}
          />
        ),
      });
    } else {
      onPressLeftHeader?.();
      if (typeof onBackHandler === 'function') {
        onBackHandler(goBack);
      } else {
        goBack();
      }
    }
    return true;
  }, [preventBack, navigator, goBack, onPressLeftHeader, onBackHandler]);

  useEffect(() => {
    const backHandler = BackHandler.addEventListener(
      'hardwareBackPress',
      goBackSafe,
    );

    return () => backHandler.remove();
  }, [goBackSafe]);

  return (
    <View style={styles.headerLeft}>
      <NavigationButton
        accessibilityLabel="btn_navigation_back"
        icon="arrow-back"
        tintColor={tintColor}
        onPress={goBackSafe}
      />
    </View>
  );
};

const styles = StyleSheet.create({
  headerLeft: {
    marginLeft: 8,
  },
});

export { HeaderLeft };
