import React, {useCallback, useEffect} from 'react';
import {StyleProp, ViewStyle} from 'react-native';
import Animated from 'react-native-reanimated';
import {useSafeAreaInsets} from 'react-native-safe-area-context';
import {
  KeyboardController,
  useKeyboardController,
} from 'react-native-keyboard-controller';
import {IconX} from '@tabler/icons-react-native';
import {IconButton} from '@components/_HuGo';
import {useBackHandler} from '@hooks/useBackHandler';
import {useInstanceProp} from '@redux/selectors';
import {useTheme} from '@shared/theme';
import {isAndroid} from '@shared/utils';

import {styles} from './styles';

interface Props {
  onClose: () => void;
  style?: StyleProp<ViewStyle>;
}

function CloseButton({onClose, style}: Props) {
  const instanceColor = useInstanceProp('color');
  const keyboardController = useKeyboardController();
  const {top: marginTop} = useSafeAreaInsets();
  const {theme} = useTheme();

  const onGoBack = useCallback(() => {
    onClose();
    return true;
  }, [onClose]);

  useBackHandler(onGoBack);

  // TODO: Delete this when react-native-keyboard-controller is enabled for Android
  useEffect(() => {
    if (isAndroid) {
      keyboardController.setEnabled(true);
      return () => {
        KeyboardController.dismiss();
        setTimeout(() => {
          keyboardController.setEnabled(false);
        }, 500);
      };
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return (
    <Animated.View
      style={[
        styles.closeButton,
        {backgroundColor: instanceColor, marginTop},
        style,
      ]}>
      <IconButton
        hitSlop={12}
        Icon={IconX}
        iconColor={theme.white}
        onPress={onClose}
        variant="flat"
      />
    </Animated.View>
  );
}

export default CloseButton;
