import React, { useContext, useRef } from 'react';
import { Dimensions, StyleSheet, TouchableOpacity, View } from 'react-native';
import { PopupPromotionProps } from './types';
import { ApplicationContext, MiniAppContext } from '../Context';
import { Image } from '../Image';
import { Colors, Radius, Spacing } from '../Consts';
import { Icon } from '../Icon';

const PopupPromotion: React.FC<PopupPromotionProps> = ({
  image,
  onIconClose,
  onRequestClose,
  onActionClick,
}) => {
  const context = useContext<any>(MiniAppContext);
  const { theme, navigator } = useContext(ApplicationContext);
  const { width: widthDevice } = Dimensions.get('window');
  const closeAction = useRef('touch_outside');

  const showBaseLineDebug = context?.features?.showBaseLineDebug ?? false;

  /**
   * on action popup
   * @param callback
   */
  const onAction = (callback?: () => void) => {
    if (typeof onRequestClose === 'function') {
      onRequestClose?.(callback);
    } else {
      navigator?.pop();
      callback?.();
    }
  };

  /**
   * build close action
   */
  const buildCloseIcon = () => {
    return (
      <View style={styles.iconCloseContainer}>
        <TouchableOpacity
          accessibilityLabel={'ic_popup_close'}
          onPress={() => {
            closeAction.current = 'icon_close';
            onAction(onIconClose);
          }}
          style={styles.iconButton}
        >
          <View
            style={[
              styles.iconClose,
              {
                backgroundColor: theme.colors.text.default,
                borderColor: theme.colors.background.surface,
              },
            ]}
          >
            <Icon
              source="navigation_close"
              color={theme.colors.background.surface}
              size={14}
            />
          </View>
        </TouchableOpacity>
      </View>
    );
  };

  return (
    <View
      accessibilityLabel={'popup_promotion'}
      style={showBaseLineDebug && styles.debugBaseLine}
    >
      <TouchableOpacity onPress={() => onAction(onActionClick)}>
        <Image
          source={{
            uri: image,
          }}
          resizeMode="contain"
          style={[
            styles.container,
            {
              width: widthDevice - Spacing.XL * 2,
            },
          ]}
        />
      </TouchableOpacity>
      {buildCloseIcon()}
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    aspectRatio: 0.5625, // 9:16
    width: '100%',
  },
  debugBaseLine: { borderWidth: 1, borderColor: Colors.green_06 },
  iconCloseContainer: {
    width: '100%',
    flexDirection: 'row',
    justifyContent: 'center',
    marginTop: Spacing.S,
  },
  iconButton: {
    padding: 8,
  },
  iconClose: {
    width: 20,
    height: 20,
    alignItems: 'center',
    justifyContent: 'center',
    borderRadius: Radius.M,
    borderWidth: 2,
  },
});

export default PopupPromotion;
