/* @ts-ignore */
import React, {Component} from 'react';
import PropTypes from 'prop-types';
 
import { Animated,
  I18nManager,
  Image,
  PanResponder,
  Text,
  TouchableOpacity,
  View, 
  TextStyle, 
  RegisteredStyle, 
  ImageStyle, 
  ViewStyle  } from 'react-native';

const styles = {
  button: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
  },
  animated: {
    borderWidth: 0,
    position: 'absolute',
  },
};


export interface ISwitchSelectorOption {
  label: string;
  value: string | number;
  customIcon?: JSX.Element;
  imageIcon?: string;
  activeColor?: string;
  accessibilityLabel?: string;
  testID?: string;
}

export interface ISwitchSelectorProps {
  options: ISwitchSelectorOption[];
  initial?: number;
  value?: number;
  onPress(value: string | number | ISwitchSelectorOption): void;
  fontSize?: number;
  selectedColor?: string;
  buttonMargin?: number;
  buttonColor?: string;
  textColor?: string;
  backgroundColor?: string;
  borderColor?: string;
  borderRadius?: number;
  hasPadding?: boolean;
  animationDuration?: number;
  valuePadding?: number;
  height?: number;
  bold?: boolean;
  textStyle?: TextStyle;
  selectedTextStyle?: TextStyle | RegisteredStyle<TextStyle>;
  textCStyle?: TextStyle | RegisteredStyle<TextStyle>;
  selectedTextContainerStyle?: TextStyle | RegisteredStyle<TextStyle>;
  imageStyle?: ImageStyle | RegisteredStyle<ImageStyle>;
  style?: ViewStyle | RegisteredStyle<ViewStyle>;
  returnObject?: boolean;
  disabled?: boolean;
  disableValueChangeOnPress?: boolean;
  accessibilityLabel?: string;
  testID?: string;
  textContainerStyle: TextStyle,
  borderWidth: number,
}


export default class SwitchSelector extends Component<ISwitchSelectorProps> {
  constructor(props:ISwitchSelectorProps) {
    super(props);
    const { initial, options } = props;
    this.state = {
      selected: initial,
    };

     // @ts-ignore
    this.panResponder = PanResponder.create({
      onStartShouldSetPanResponder: this.shouldSetResponder,
      onMoveShouldSetPanResponder: this.shouldSetResponder,
      onPanResponderRelease: this.responderEnd,
      onPanResponderTerminate: this.responderEnd,
    });

    // @ts-ignore
    this.animatedValue = new Animated.Value(
      initial
        ? I18nManager.isRTL
          ? -(initial / options.length)
          : initial / options.length
        : 0,
    );
  }

  // @ts-ignore
  componentDidUpdate(prevProps) {
    const { value, disableValueChangeOnPress } = this.props;
    if (prevProps.value !== value) {
      this.toggleItem(value, !disableValueChangeOnPress);
    }
  }
  // @ts-ignore
  getSwipeDirection(gestureState) {
    const { dx, dy, vx } = gestureState;
    // 0.1 velocity
    if (Math.abs(vx) > 0.1 && Math.abs(dy) < 80) {
      return dx > 0 ? 'RIGHT' : 'LEFT';
    }
    return null;
  }

  getBgColor() {
    // @ts-ignore
    const { selected } = this.state;
    const { options, buttonColor } = this.props;
    if (selected === -1) {
      return 'transparent';
    }
    return options[selected].activeColor || buttonColor;
  }

  // @ts-ignore
  responderEnd = (evt, gestureState) => {
    const { disabled, options } = this.props;
    // @ts-ignore
    const { selected } = this.state;

    if (disabled) return;
    const swipeDirection = this.getSwipeDirection(gestureState);
    if (
      swipeDirection === 'RIGHT'
      && selected < options.length - 1
    ) {
      this.toggleItem(selected + 1);
    } else if (swipeDirection === 'LEFT' && selected > 0) {
      this.toggleItem(selected - 1);
    }
  };

  // @ts-ignore
  shouldSetResponder = (evt, gestureState) => evt.nativeEvent.touches.length === 1
    && !(Math.abs(gestureState.dx) < 5 && Math.abs(gestureState.dy) < 5);

  // @ts-ignore
  animate = (value, last) => {
    const { animationDuration } = this.props;
    // @ts-ignore
    this.animatedValue.setValue(last);
    // @ts-ignore
    Animated.timing(this.animatedValue, {
      toValue: value,
      duration: animationDuration,
      useNativeDriver: true,
    }).start();
  };

  // @ts-ignore
  toggleItem = (index, callOnPress = true) => {
    // @ts-ignore
    const { selected } = this.state;
    const { options, returnObject, onPress } = this.props;
    if (options.length <= 1 || index === null || isNaN(index)) return;
    this.animate(
      I18nManager.isRTL ? -(index / options.length) : index / options.length,
      I18nManager.isRTL
        ? -(selected / options.length)
        : selected / options.length,
    );
    if (callOnPress && onPress) {
      onPress(returnObject ? options[index] : options[index].value);
    } else {
      console.log('Call onPress with value: ', options[index].value);
    }
    this.setState({ selected: index });
  };

  render() {
    const {
      style,
      textStyle,
      selectedTextStyle,
      textContainerStyle,
      selectedTextContainerStyle,
      imageStyle,
      textColor,
      selectedColor,
      fontSize,
      backgroundColor,
      borderColor,
      borderRadius,
      borderWidth,
      hasPadding,
      valuePadding,
      height,
      bold,
      disabled,
      buttonMargin,
      options,
    } = this.props;

    // @ts-ignore
    const { selected, sliderWidth } = this.state;

    const optionsMap = options.map((element, index) => {
      const isSelected = selected === index;

      return (
        <TouchableOpacity
          key={index}
          disabled={disabled}
          style={[
            // @ts-ignore
            styles.button,
            isSelected ? selectedTextContainerStyle : textContainerStyle,
          ]}
          onPress={() => this.toggleItem(index)}
          accessibilityLabel={element.accessibilityLabel}
          testID={element.testID}
        >
          {typeof element.customIcon === 'function'
          // @ts-ignore
            ? element.customIcon(isSelected)
            : element.customIcon}
          {element.imageIcon && (
            <Image
              // @ts-ignore
              source={element.imageIcon}
              style={[
                {
                  height: 30,
                  width: 30,
                  tintColor: isSelected ? selectedColor : textColor,
                },
                imageStyle,
              ]}
            />
          )}
          <Text
            style={[
              {
                fontSize,
                fontWeight: bold ? 'bold' : 'normal',
                textAlign: 'center',
                color: isSelected ? selectedColor : textColor,
                backgroundColor: 'transparent',
              },
              isSelected ? selectedTextStyle : textStyle,
            ]}
            numberOfLines={1}
          >
            {element.label}
          </Text>
        </TouchableOpacity>
      );
    });

    return (
      <View
        style={[{ flexDirection: 'row' }, style]}
        accessibilityLabel={this.props.accessibilityLabel}
        testID={this.props.testID}
      >
        
        <View 
          /* @ts-ignore */
          {...this.panResponder.panHandlers} style={{ flex: 1 }}>
          <View
            style={{
              borderRadius,
              backgroundColor,
              /* @ts-ignore */
              height: height + buttonMargin * 2,
            }}
            /* @ts-ignore */
            onLayout={(event) => {
              const { width } = event.nativeEvent.layout;
              this.setState({
                sliderWidth: width - (hasPadding ? 2 : 0),
              });
            }}
          >
            <View
              style={{
                flex: 1,
                flexDirection: 'row',
                borderColor,
                borderRadius,
                borderWidth: hasPadding ? borderWidth : 0,
                alignItems: 'center',
              }}
            >
              {!!sliderWidth && (
                <Animated.View
                  style={[
                    {
                      height: hasPadding
                      /* @ts-ignore */
                        ? height - valuePadding * 2 - borderWidth * 2
                        : height,
                      backgroundColor: this.getBgColor(),
                      width:
                        sliderWidth / options.length
                        /* @ts-ignore */
                        - ((hasPadding ? valuePadding : 0) + buttonMargin * 2),
                      transform: [
                        {
                          /* @ts-ignore */
                          translateX: this.animatedValue.interpolate({
                            inputRange: [0, 1],
                            outputRange: [
                              hasPadding ? valuePadding : 0,
                              sliderWidth
                              /* @ts-ignore */
                                - (hasPadding ? valuePadding : 0),
                            ],
                          }),
                        },
                      ],
                      borderRadius,
                      margin: buttonMargin,
                    },
                    // @ts-ignore
                    styles.animated,
                  ]}
                />
              )}
              {optionsMap}
            </View>
          </View>
        </View>
      </View>
    );
  }
}

/* @ts-ignore */
SwitchSelector.defaultProps = {
  style: {
    marginHorizontal: 20, 
    marginVertical: 5, 
    flex: 1},
  textStyle: {flex: 1},
  selectedTextStyle: { fontWeight: 'bold' },
  textContainerStyle: {flexGrow: 1, paddingHorizontal: 20, marginHorizontal: 5},
  selectedTextContainerStyle: {paddingHorizontal: 20},
  imageStyle: {},
  options: [],
  textColor: "#67758B",
  selectedColor: '#ffffff',
  fontSize: 14,
  backgroundColor: '#ffffff',
  borderColor: '#f4f5f9',
  borderRadius: 50,
  borderWidth: 1,
  hasPadding: true,
  valuePadding: 1,
  height: 40,
  bold: false,
  buttonMargin: 0,
  buttonColor: "#d22e2e",
  returnObject: false,
  animationDuration: 100,
  disabled: false,
  disableValueChangeOnPress: false,
  initial: -1,
  value: 1,
  onPress: null,
  accessibilityLabel: null,
  testID: null,
};

/* @ts-ignore */
SwitchSelector.propTypes = {
  style: PropTypes.oneOfType([PropTypes.object, PropTypes.array]),
  textStyle: PropTypes.object,
  selectedTextStyle: PropTypes.object,
  textContainerStyle: PropTypes.object,
  selectedTextContainerStyle: PropTypes.object,
  imageStyle: PropTypes.object,
  options: PropTypes.array,
  textColor: PropTypes.string,
  selectedColor: PropTypes.string,
  fontSize: PropTypes.number,
  backgroundColor: PropTypes.string,
  borderColor: PropTypes.string,
  borderRadius: PropTypes.number,
  borderWidth: PropTypes.number,
  hasPadding: PropTypes.bool,
  valuePadding: PropTypes.number,
  height: PropTypes.number,
  bold: PropTypes.bool,
  buttonMargin: PropTypes.number,
  buttonColor: PropTypes.string,
  returnObject: PropTypes.bool,
  animationDuration: PropTypes.number,
  disabled: PropTypes.bool,
  disableValueChangeOnPress: PropTypes.bool,
  initial: PropTypes.number,
  value: PropTypes.number,
  onPress: PropTypes.func,
  accessibilityLabel: PropTypes.string,
  testID: PropTypes.string,
};
