import React, { useContext, useRef, useState } from 'react';
import {
  Dimensions,
  ScrollView,
  StyleSheet,
  TouchableOpacity,
  View,
} from 'react-native';
import { ApplicationContext, MiniAppContext } from '../Context';
import { Button } from '../Button';
import { Colors, Radius, Spacing, Styles } from '../Consts';
import { Icon } from '../Icon';
import { Image } from '../Image';
import { Text, useScaleSize } from '../Text';
import { PopupNotifyProps } from './types';
import { runOnJS } from 'react-native-reanimated';

const PopupNotify: React.FC<PopupNotifyProps> = ({
  image,
  title = 'Title',
  description = 'Description',
  error,
  secondary,
  primary,
  buttonDirection = 'row',
  onIconClose,
  onRequestClose,
}) => {
  const context = useContext<any>(MiniAppContext);
  const { theme, navigator, translate } = useContext(ApplicationContext);
  const [scrollContent, setScrollContent] = useState(false);
  const { width: widthDevice } = Dimensions.get('window');
  const scaledMaxHeight = useScaleSize(172);

  const showBaseLineDebug = context?.features?.showBaseLineDebug ?? false;
  const closeAction = useRef('touch_outside');
  let descriptionStyle = {};
  let Description: any = View;
  if (scrollContent) {
    Description = ScrollView;
    descriptionStyle = { maxHeight: scaledMaxHeight };
  }

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

  /**
   *  build main action of popup
   */
  const buildAction = () => {
    const renderRow = () => {
      return (
        <View style={Styles.row}>
          {!!secondary?.title && (
            <>
              <View style={Styles.flex}>
                <Button
                  title={secondary?.title}
                  type="text"
                  size="medium"
                  onPress={() => {
                    closeAction.current = 'button_action';
                    onAction(secondary?.onPress);
                  }}
                  accessibilityLabel={'btn_popup_cancel'}
                />
              </View>
              <View style={styles.buttonSpace} />
            </>
          )}
          <View style={Styles.flex}>
            <Button
              title={primary.title}
              size="medium"
              onPress={() => {
                closeAction.current = 'button_action';
                onAction(primary.onPress);
              }}
              accessibilityLabel={'btn_popup_allow'}
            />
          </View>
        </View>
      );
    };
    const renderColumn = () => {
      return (
        <View style={Styles.columnCenter}>
          <Button
            accessibilityLabel={'btn_popup_allow'}
            title={primary.title}
            size="medium"
            onPress={() => {
              closeAction.current = 'button_action';
              onAction(primary.onPress);
            }}
          />
          {!!secondary?.title && (
            <>
              <View style={styles.buttonSpace} />
              <Button
                accessibilityLabel={'btn_popup_cancel'}
                title={secondary?.title}
                type="text"
                size="medium"
                onPress={() => {
                  closeAction.current = 'button_action';
                  onAction(secondary?.onPress);
                }}
              />
            </>
          )}
        </View>
      );
    };

    if (buttonDirection === 'auto') {
      if (
        secondary?.title &&
        (secondary.title.length > 12 || primary.title.length > 12)
      ) {
        return renderColumn();
      }
      return renderRow();
    }
    if (buttonDirection === 'row') {
      return renderRow();
    }
    return renderColumn();
  };

  /**
   * build close action
   */
  const buildCloseIcon = () => {
    if (typeof onIconClose === 'function') {
      return (
        <TouchableOpacity
          accessibilityLabel={'ic_popup_close'}
          style={styles.iconCloseContainer}
          onPress={() => {
            closeAction.current = 'icon_close';
            onAction(onIconClose);
          }}
        >
          <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>
      );
    }
  };

  return (
    <View
      accessibilityLabel={'popup_notify'}
      style={[
        styles.container,
        {
          backgroundColor: theme.colors.background.surface,
          width: widthDevice - Spacing.XL * 2,
        },
        showBaseLineDebug && styles.debugBaseLine,
      ]}
    >
      {!!image && <Image source={{ uri: image }} style={styles.image} />}
      <View style={styles.content}>
        <Text
          typography={'header_default_bold'}
          numberOfLines={3}
          accessibilityLabel={'title_popup_notify'}
        >
          {title}
        </Text>
        <Description style={[styles.description, descriptionStyle]}>
          {typeof description === 'string' ? (
            <Text
              accessibilityLabel={'description_popup_notify'}
              typography={'body_default_regular'}
              onTextLayout={({ nativeEvent: { lines } }) => {
                const enableScroll = lines.length > 8.5;
                if (enableScroll !== scrollContent) {
                  setScrollContent(enableScroll);
                }
              }}
            >
              {description}
            </Text>
          ) : (
            description
          )}
        </Description>
        {!!error && (
          <View style={styles.information}>
            <Text
              accessibilityLabel={'description_popup_notify'}
              typography={'description_xs_regular'}
              color={theme.colors.text.hint}
              numberOfLines={1}
            >
              {translate?.('errorCode')}
              {error}
            </Text>
          </View>
        )}
      </View>
      <View style={styles.contentAction}>{buildAction()}</View>
      {buildCloseIcon()}
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    borderRadius: Radius.L,
  },
  debugBaseLine: { borderWidth: 1, borderColor: Colors.green_06 },
  image: {
    borderTopLeftRadius: Radius.L,
    borderTopRightRadius: Radius.L,
    aspectRatio: 1.7777,
    overflow: 'hidden',
  },
  content: { padding: Spacing.XL },
  description: {
    marginTop: Spacing.S,
  },
  information: {
    marginTop: Spacing.S,
  },
  contentAction: {
    paddingHorizontal: Spacing.XL,
    paddingBottom: Spacing.XL,
  },
  buttonSpace: {
    width: Spacing.S,
    height: Spacing.S,
  },
  iconCloseContainer: {
    position: 'absolute',
    top: -Spacing.M,
    right: -Spacing.M,
    padding: Spacing.XS,
  },
  iconClose: {
    width: 20,
    height: 20,
    alignItems: 'center',
    justifyContent: 'center',
    borderRadius: Radius.M,
    borderWidth: 2,
  },
});

export default PopupNotify;
