import React, { useState } from 'react';
import { GestureResponderEvent, Platform, Pressable } from 'react-native';
import { fp as _ } from '../utils/fp';
import { SBox } from '../s-components/layout/s-box';
import { Icon } from './icon';
import { TColor, TIconName } from '../types';

type TProps = {
  color?: TColor;
  left?: number;
  marginTop?: number;
  onPress: (event: GestureResponderEvent) => void;
  top?: number;
  fixed?: boolean;
  iconName?: TIconName;
  testID?: string;
};

export const BackButton: React.FC<TProps> = props => {
  const [pressed, setPressed] = useState(false);
  const { marginTop, onPress, top, color, left, fixed, iconName } = props;
  const defaultMarginTop = Platform.OS === 'ios' ? 26 : 27;
  const topValue = _.isNotNil(top) ? top : '50%';
  const marginTopValue = _.isNotNil(marginTop) ? marginTop : defaultMarginTop;
  const styles = fixed
    ? {}
    : {
        position: 'absolute',
        top: topValue,
        left,
        marginTop: marginTopValue,
      };

  return (
    <SBox {...styles}>
      <Pressable
        onPress={onPress as () => void}
        onPressIn={() => {
          setPressed(true);
        }}
        onPressOut={() => {
          setPressed(false);
        }}
        testID="back-button"
      >
        <SBox
          width={44}
          height={44}
          justifyContent="center"
          alignItems="center"
          style={{ opacity: pressed ? 0.7 : 1 }}
        >
          <Icon
            name={
              iconName || (Platform.OS === 'ios' ? 'ios-back' : 'android-back')
            }
            size={32}
            color={color}
          />
        </SBox>
      </Pressable>
    </SBox>
  );
};

BackButton.defaultProps = {
  color: 'white',
  left: 15,
};
