import React from "react";
import {
  Animated,
  Keyboard,
  StyleSheet,
  View as RNView,
  ViewProps as RNViewProps,
} from "react-native";
import LinearGradient, {
  LinearGradientProps,
} from "react-native-linear-gradient";
import Reanimated from "react-native-reanimated";
import { Styled, StyledProps } from "./Styled";

export type ViewProps = StyledProps &
  RNViewProps & {
    refView?: any;
    animatedStyle?: any;
    reanimatedStyle?: any;
    gradientProps?: LinearGradientProps;
    dismissOnTouchOutside?: boolean;
  };

export const View = (props: ViewProps) => {
  const {
    refView,
    animatedStyle,
    reanimatedStyle,
    gradientProps,
    children,
    dismissOnTouchOutside,
    onStartShouldSetResponder,
  } = props;

  const MyView = reanimatedStyle
    ? Reanimated.View
    : animatedStyle
    ? Animated.View
    : RNView;

  const _onStartShouldSetResponder = (e: any) => {
    if (onStartShouldSetResponder) onStartShouldSetResponder(e);
    else dismissOnTouchOutside && Keyboard.dismiss();
    return false;
  };

  return (
    <Styled {...props}>
      {(style: any) => (
        <MyView
          {...props}
          ref={refView}
          style={[style, animatedStyle, reanimatedStyle]}
          onStartShouldSetResponder={_onStartShouldSetResponder}
        >
          {gradientProps && (
            <LinearGradient
              {...gradientProps}
              style={StyleSheet.absoluteFill}
            />
          )}
          {children}
        </MyView>
      )}
    </Styled>
  );
};
