import React, {useCallback, useContext, useEffect, useRef} from 'react';
import {
  findNodeHandle,
  StyleProp,
  StyleSheet,
  TextStyle,
  TouchableOpacity,
  View,
  ViewStyle,
} from 'react-native';
import {INativeAdContext, NativeAdContext} from './context';
import {Text, TextProps} from '@momo-kits/foundation';

interface ICallToActionViewProps {
  style?: StyleProp<ViewStyle>;
  allowFontScaling?: boolean;
  textStyle?: StyleProp<TextStyle>;
  textProps?: StyleProp<TextProps>;
  allCaps?: boolean;
  buttonAndroidStyle?: StyleProp<ViewStyle>;
}

const CallToActionView = ({
  allowFontScaling = true,
  textStyle,
  allCaps,
  textProps,
  style,
}: ICallToActionViewProps) => {
  const {nativeAd, nativeAdView} =
    useContext<INativeAdContext>(NativeAdContext);
  const callToActionRef = useRef();
  const _onLayout = useCallback(() => {
    if (!nativeAdView) return;

    nativeAdView.setNativeProps({
      callToAction: findNodeHandle(callToActionRef.current),
    });
  }, [nativeAdView, callToActionRef]);

  useEffect(() => {
    _onLayout();
  }, [nativeAd, nativeAdView]);

  const renderText = (
    <Text allowFontScaling={allowFontScaling} style={textStyle} {...textProps}>
      {nativeAd
        ? allCaps
          ? nativeAd.callToAction?.toUpperCase()
          : nativeAd.callToAction
        : null}
    </Text>
  );

  return (
    <View style={styles.container}>
      <ButtonView
        style={style}
        activeOpacity={0.85}
        ref={callToActionRef}
        onLayout={_onLayout}>
        {renderText}
      </ButtonView>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    justifyContent: 'center',
    alignItems: 'center',
  },
  textwrapper: {
    position: 'absolute',
    zIndex: 10,
  },
});

const ButtonView = TouchableOpacity;

export default CallToActionView;
