import LinearGradient from 'react-native-linear-gradient';
import { Animated, StyleSheet, View } from 'react-native';
import React, { useContext } from 'react';
import { HeaderBackgroundProps } from '../types';
import { ApplicationContext, MiniAppContext } from '../../Context';
import { Colors, Styles } from '../../Consts';
import { Image } from '../../Image';
import BackgroundImageView from './BackgroundImageView';

const LinearGradientAnimated = Animated.createAnimatedComponent(LinearGradient);

/**
 * header background for default
 */
const HeaderBackground: React.FC<HeaderBackgroundProps> = ({
  animatedValue = new Animated.Value(0),
  useGradient = true,
  useShadowHeader = true,
  gradientColor: customGradientColor,
  headerBackground,
}) => {
  const { theme } = useContext(ApplicationContext);
  const context = useContext<any>(MiniAppContext);
  const gradientColor = customGradientColor ?? theme.colors.gradient;
  const headerImage = headerBackground ?? theme.assets?.headerBackground;

  const showBaseLineDebug = context?.features?.showBaseLineDebug ?? false;

  const opacityBackground = animatedValue?.interpolate({
    inputRange: [0, 52],
    outputRange: [0, 1],
    extrapolate: 'clamp',
  });

  return (
    <View style={[Styles.flex, showBaseLineDebug && styles.debugBaseLine]}>
      <BackgroundImageView
        useShadowHeader={useShadowHeader}
        heightHeader={'100%'}
        opacityBackground={opacityBackground}
        headerBackground={headerImage}
      />
      <View style={styles.gradientContainer}>
        {useGradient && !!gradientColor && (
          <LinearGradientAnimated
            colors={[gradientColor, gradientColor + '00']}
            style={styles.extendedHeader}
          >
            {!!headerImage && (
              <Image
                style={styles.headerBackground}
                source={{ uri: headerImage }}
                loading={false}
              />
            )}
          </LinearGradientAnimated>
        )}
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  gradientContainer: {
    width: '100%',
    height: '100%',
    position: 'absolute',
    overflow: 'hidden',
  },
  extendedHeader: {
    aspectRatio: 375 / 154,
    position: 'absolute',
    width: '100%',
  },
  headerBackground: {
    width: '100%',
    position: 'absolute',
    aspectRatio: 375 / 154,
  },
  debugBaseLine: { borderWidth: 1, borderColor: Colors.green_06 },
});

export { HeaderBackground };
