import React, { useState, useEffect } from 'react';
import { AccessibilityInfo, LayoutChangeEvent } from 'react-native';
import { Box } from '../Box';
import { Text } from '../Text';
import { useTheme } from '../../theme/ThemeProvider';
import SwipeThumb from './components/SwipeThumb';
import { LoadingContainer } from '../Loading/LoadingContainer';

export interface ISwipeButton {
  title: string;
  disabled?: boolean;
  disableResetOnTap?: boolean;
  enableReverseSwipe?: boolean;
  forceReset?: () => void;
  loading?: boolean;
  height?: number;
  onSwipeFail?: () => void;
  onSwipeStart?: () => void;
  onSwipeSuccess: () => void;
  resetAfterSuccessAnimDelay?: number;
  resetAfterSuccessAnimDuration?: number;
  shouldResetAfterSuccess?: boolean;
  swipeSuccessThreshold?: number; // Ex: 60. Swipping 60% will be considered as successful swipe
  thumbIconWidth?: number;
}

export const SwipeButton = ({
  title,
  disabled = false,
  height = 50,
  loading,
  ...rest
}: ISwipeButton) => {
  const [layoutWidth, setLayoutWidth] = useState<number>(0);
  const [screenReaderEnabled, setScreenReaderEnabled] =
    useState<boolean>(false);
  const [isUnmounting, setIsUnmounting] = useState<boolean>(false);
  const { fonts, colors } = useTheme();

  /**
   * Retrieve layoutWidth to set maximum swipeable area.
   * Correct layout width will be received only after first render but we need it before render.
   * So render SwipeThumb only if layoutWidth > 0
   */
  const onLayoutContainer = async (event: LayoutChangeEvent) => {
    if (isUnmounting || layoutWidth) return;
    setLayoutWidth(event.nativeEvent.layout.width);
  };

  useEffect(() => {
    const handleScreenReaderToggled = (isEnabled: boolean) => {
      if (isUnmounting || screenReaderEnabled === isEnabled) return;
      setScreenReaderEnabled(isEnabled);
    };
    setIsUnmounting(false);

    const suscription = AccessibilityInfo.addEventListener(
      'change',
      handleScreenReaderToggled
    );

    AccessibilityInfo.isScreenReaderEnabled().then((isEnabled) => {
      if (isUnmounting) {
        return;
      }
      setScreenReaderEnabled(isEnabled);
    });

    return () => {
      setIsUnmounting(true);
      suscription.remove();
    };
  }, [isUnmounting, screenReaderEnabled]);

  return (
    <Box
      borderRadius={6}
      justifyContent={'center'}
      // eslint-disable-next-line react-native/no-inline-styles
      style={{
        backgroundColor: disabled ? colors.gray100 : '#D4FDEC',
      }}
      onLayout={onLayoutContainer}
    >
      {loading ? (
        <Box
          // eslint-disable-next-line react-native/no-inline-styles
          style={{
            position: 'absolute',
            alignSelf: 'center',
            zIndex: 999,
          }}
        >
          <LoadingContainer
            pt="spacing-none"
            pb="spacing-none"
            colorDot="white"
            size="small"
          />
        </Box>
      ) : (
        <Text
          color={disabled ? 'white' : 'green'}
          variant={'body'}
          fontFamily={fonts.caustenRoundBold}
          numberOfLines={1}
          ellipsizeMode={'tail'}
          importantForAccessibility={
            screenReaderEnabled ? 'no-hide-descendants' : undefined
          }
          // eslint-disable-next-line react-native/no-inline-styles
          style={{
            alignSelf: 'center',
            position: 'absolute',
          }}
        >
          {title}
        </Text>
      )}
      {layoutWidth > 0 && (
        <SwipeThumb
          title={title}
          disabled={disabled}
          layoutWidth={layoutWidth}
          screenReaderEnabled={screenReaderEnabled}
          thumbIconHeight={height}
          isLoading={!!loading}
          resetAfterSuccessAnimDuration={1000}
          resetAfterSuccessAnimDelay={1000}
          {...rest}
        />
      )}
    </Box>
  );
};
