import React, { useCallback, useContext, useEffect, useState } from 'react';
import {
  Platform,
  StyleSheet,
  TouchableOpacity,
  View,
  ViewStyle,
} from 'react-native';
import { NavigationButton } from './NavigationButton';
import { ApplicationContext, MiniAppContext } from '../../Context';
import { Colors, Spacing, Styles } from '../../Consts';
import { PopupNotify } from '../../Popup';
import { Tool, ToolGroup } from '../types';
import { Icon } from '../../Icon';
import { Text } from '../../Text';

const DID_SYNC_NEW_HOME = 'did_sync_new_home';

/**
 * main component for header right
 */
const HeaderRight: React.FC<any> = props => {
  const { translate } = useContext(ApplicationContext);
  const { headerRight = {} } = props;
  const { useOnBoarding = false, buttonOnBoarding, onPress } = headerRight;

  if (typeof props.headerRight === 'function') {
    return props.headerRight(props);
  }

  if (useOnBoarding && onPress) {
    return (
      <TouchableOpacity onPress={onPress} style={styles.onBoarding}>
        <Text typography={'action_s_bold'}>
          {buttonOnBoarding || translate?.('skip')}
        </Text>
      </TouchableOpacity>
    );
  }

  return (
    <View style={styles.headerRightButton}>
      <HeaderToolkitAction {...props.headerRight} tintColor={props.tintColor} />
    </View>
  );
};

/**
 * Header toolkit action
 */
const HeaderToolkitAction: React.FC<any> = ({
  tintColor,
  preventClose,
  useSystemTools = true,
  useShortcut = false,
  useMore = false,
  tools = [],
  useCloseIcon = false,
}) => {
  const { navigator } = useContext(ApplicationContext);
  const context = useContext<any>(MiniAppContext);

  const [isFavorite, setIsFavorite] = useState<boolean>(false);
  const [isLoading, setIsLoading] = useState(false);

  /**
   * check app is favorite
   */
  const checkAppIsFavorite = useCallback(
    () =>
      navigator?.maxApi?.dispatchFunction?.(
        'isFavoriteApp',
        { code: context?.code },
        (result: boolean) => {
          setIsFavorite(result);
        },
      ),
    [context?.code, navigator?.maxApi],
  );

  useEffect(() => {
    if (useShortcut) {
      checkAppIsFavorite();

      const favoriteObserver = navigator?.maxApi?.observer?.(
        DID_SYNC_NEW_HOME,
        (updatedData: any) => {
          const status = updatedData?.items?.includes(context?.code);
          setIsFavorite(status);
        },
      );
      return () => {
        favoriteObserver?.remove?.();
      };
    }
  }, [useShortcut, context, checkAppIsFavorite, navigator?.maxApi]);

  let buttonStyle: ViewStyle = {};
  if (tintColor === Colors.black_01 || tintColor === 'white') {
    buttonStyle = {
      backgroundColor: '#00000099',
      borderColor: '#FFFFFF33',
    };
  }

  const onDismiss = () => {
    if (useCloseIcon) {
      navigator?.maxApi?.dispatchFunction?.(
        'dismiss',
        navigator?.dismissData,
        undefined,
      );
    } else {
      navigator?.maxApi?.dispatchFunction?.('dismissAll');
    }
  };

  /**
   * close navigation container
   */
  const onClose = () => {
    const currentRoute = navigator?.ref?.current?.getCurrentRoute?.();
    context?.autoTracking?.({
      ...context,
      componentName: 'IconButton',
      componentId: 'navigation_close',
      screenName: currentRoute?.params?.screen?.name ?? currentRoute?.name,
    });

    if (preventClose) {
      navigator?.showModal({
        screen: () => (
          <PopupNotify
            {...preventClose}
            primary={{
              title: preventClose.primary.title,
              onPress: () => {
                preventClose?.primary.onPress();
                onDismiss();
              },
            }}
          />
        ),
      });
    } else {
      onDismiss();
    }
  };

  /**
   * on press shortcut
   */
  const onPressShortcut = () => {
    const currentRoute = navigator?.ref?.current?.getCurrentRoute?.();
    const expected = !isFavorite;
    context?.autoTracking?.({
      ...context,
      componentName: 'IconButton',
      componentId: `${expected ? 'pin' : 'unpin'}_shortcut`,
      screenName: currentRoute?.params?.screen?.name ?? currentRoute?.name,
    });
    setIsLoading(true);
    navigator?.maxApi?.dispatchFunction?.(
      'onToolAction',
      {
        item: {
          key: 'onFavorite',
        },
        context,
      },
      ({ success }: { success: boolean }) => {
        if (success) {
          setIsFavorite(expected);
        }
      },
    );
    setTimeout(() => {
      setIsLoading(false);
    }, 1000);
  };

  /**
   * on press help center
   */
  const onPressHelpCenter = () => {
    const currentRoute = navigator?.ref?.current?.getCurrentRoute?.();
    context?.autoTracking?.({
      ...context,
      componentName: 'IconButton',
      componentId: 'navigation_helpcenter',
      screenName: currentRoute?.params?.screen?.name ?? currentRoute?.name,
    });

    navigator?.maxApi?.dispatchFunction?.('showHelpCenter', context);
  };

  /**
   * on press icon more
   */
  const onPressIconMore = () => {
    const currentRoute = navigator?.ref?.current?.getCurrentRoute?.();
    context?.autoTracking?.({
      ...context,
      componentName: 'IconButton',
      componentId: 'navigation_more',
      screenName: currentRoute?.params?.screen?.name ?? currentRoute?.name,
    });

    navigator?.maxApi?.dispatchFunction?.(
      'showTools',
      {
        useSystemTools,
        tools,
        context,
      },
      (key: string) => {
        for (const group of tools) {
          const pressedTool = group?.items?.find?.(
            (tool: Tool) => tool?.key === key,
          );
          if (pressedTool) {
            pressedTool?.onPress();
            break;
          }
        }
      },
    );
  };

  let iconShortcut = isFavorite ? 'pin_star_checked' : 'pin_star';
  let shortcutOnPress = onPressShortcut;
  const totalTools = tools.reduce(
    (count: number, group: ToolGroup) => count + group?.items?.length,
    0,
  );
  const showIconMore = tools && totalTools > 1;
  const isHaveOneTool = tools && totalTools === 1;

  if (showIconMore || useMore) {
    iconShortcut = 'navigation_more_icon';
    shortcutOnPress = onPressIconMore;
  } else if (isHaveOneTool) {
    const singleTool = tools.find(
      (group: ToolGroup) => group?.items?.length === 1,
    )?.items[0];
    iconShortcut = singleTool?.icon;
    shortcutOnPress = () => {
      singleTool?.onPress?.();
      const currentRoute = navigator?.ref?.current?.getCurrentRoute?.();
      context?.autoTracking?.({
        ...context,
        componentName: 'IconButton',
        componentId: 'navigation_shortcut',
        screenName: currentRoute?.params?.screen?.name ?? currentRoute?.name,
      });
    };
  }

  const showBadge = tools.some((group: ToolGroup) =>
    group?.items?.some?.(tool => tool?.showBadge),
  );

  return (
    <View style={Styles.row}>
      {useShortcut && (
        <NavigationButton
          disabled={isLoading}
          icon={iconShortcut}
          onPress={shortcutOnPress}
          tintColor={tintColor}
          showBadge={showBadge}
        />
      )}
      <View
        style={[
          styles.toolkitContainer,
          buttonStyle,
          {
            width: context.appId !== 'vn.momo.helpcenter' ? 65 : 28,
          },
        ]}
      >
        {context.appId !== 'vn.momo.helpcenter' && (
          <>
            <TouchableOpacity
              accessibilityLabel={'btn_navigation_help_center'}
              style={styles.toolkitButton}
              onPress={onPressHelpCenter}
              hitSlop={{ top: 7, bottom: 7, left: 7, right: 0 }}
            >
              <Icon color={tintColor} source={'help_center'} size={20} />
            </TouchableOpacity>
            <View style={[styles.divider, { backgroundColor: tintColor }]} />
          </>
        )}
        <TouchableOpacity
          accessibilityLabel={'btn_navigation_close'}
          onPress={onClose}
          style={styles.toolkitButton}
          hitSlop={{ top: 7, bottom: 7, left: 0, right: 7 }}
        >
          <Icon
            color={tintColor}
            source={
              useCloseIcon ? '16_navigation_close_circle' : '16_basic_home'
            }
            size={20}
          />
        </TouchableOpacity>
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  navigationButton: {
    height: 28,
    width: 28,
    borderRadius: 14,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#FFFFFF99',
    borderColor: '#00000033',
    borderWidth: 0.2,
  },
  headerBackground: {
    width: '100%',
    height: undefined,
    position: 'absolute',
    aspectRatio: 375 / 154,
  },
  headerTitleContainer: {
    alignItems: 'center',
    justifyContent: 'center',
    width: '70%',
  },
  circle: {
    width: 32,
    height: 32,
    borderRadius: 16,
    borderWidth: 0.5,
    borderColor: Colors.black_04,
  },
  dotAvatar: {
    position: 'absolute',
    width: 12,
    height: 12,
    borderRadius: 6,
    bottom: -2,
    right: -2,
    borderWidth: 2,
    borderColor: Colors.black_01,
  },
  headerButton: { paddingHorizontal: 4 },
  headerRightButton: {
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    paddingRight: Spacing.M,
  },
  toolkitContainer: {
    height: 28,
    borderRadius: 14,
    justifyContent: 'center',
    alignItems: 'center',
    flexDirection: 'row',
    backgroundColor: '#FFFFFF99',
    borderColor: '#00000033',
    borderWidth: 0.2,
    marginLeft: Spacing.S,
  },
  toolkitButton: {
    padding: 4,
  },
  divider: {
    width: 0.5,
    height: 12,
  },
  headerLeft: {
    marginLeft: 12,
  },
  badge: {
    position: 'absolute',
    top: -Spacing.S,
    right: -6,
  },
  badgeDot: {
    position: 'absolute',
    top: -Spacing.XXS,
    right: -Spacing.XXS,
  },
  badgeDotAnimation: {
    position: 'absolute',
    top: -Spacing.XS,
    right: -Spacing.XS,
  },
  gradientContainer: {
    width: '100%',
    height: '100%',
    position: 'absolute',
    overflow: 'hidden',
  },
  extendedHeader: {
    aspectRatio: 2.43,
    position: 'absolute',
    width: '100%',
  },
  verifiedDot: {
    width: 4,
    height: 4,
    borderRadius: 2,
    backgroundColor: Colors.green_03,
    position: 'absolute',
    alignSelf: 'center',
  },
  shadowHeader: {
    ...Platform.select({
      ios: {
        shadowColor: Colors.black_20,
        shadowOffset: {
          width: 3,
          height: 3,
        },
        shadowOpacity: 0.12,
        shadowRadius: 10,
      },
      android: {
        shadowColor: Colors.black_17,
        shadowOffset: {
          width: 3,
          height: 3,
        },
        shadowOpacity: 0.12,
        shadowRadius: 10,
        elevation: 10,
      },
    }),
  },
  onBoarding: {
    marginRight: Spacing.M,
  },
});

export { HeaderRight };
