import React, {useState} from 'react';
import {View, ImageBackground, Animated, LayoutChangeEvent} from 'react-native';
import {IconProps} from '@tabler/icons-react-native';
import {Gradient, GradientProps} from '@components';
import {useTheme} from '@shared/theme';
import {hexToRgb} from '@shared/colors';

import {styles} from './styles';

interface AnimatedHeaderProps {
  pictureUrl: Nullable<string>;
  animatedImageStyle: {
    transform: {scale: Animated.AnimatedInterpolation<number>}[];
    opacity: Animated.AnimatedInterpolation<number>;
  };
  onImageLayout: (event: LayoutChangeEvent) => void;
  DefaultIcon: React.ComponentType<IconProps>;
}

function AnimatedHeader({
  pictureUrl,
  animatedImageStyle,
  DefaultIcon,
  onImageLayout,
}: AnimatedHeaderProps) {
  const {theme} = useTheme();
  const [imageError, setImageError] = useState(false);

  const GRADIENT_COLORS: GradientProps['colors'] = [
    hexToRgb(theme.border.neutral.default, 0.12),
    hexToRgb(theme.border.neutral.default, 0.6),
    hexToRgb(theme.border.neutral.default, 1),
  ];

  const onImageError = () => setImageError(true);

  return (
    <Animated.View style={[styles.imageContainer, animatedImageStyle]}>
      {pictureUrl && !imageError ? (
        <ImageBackground
          onLayout={onImageLayout}
          source={{uri: pictureUrl}}
          style={styles.image}
          resizeMode="cover"
          onError={onImageError}>
          <Gradient
            start={{x: 0, y: 0.7}}
            end={{x: 0, y: 1}}
            colors={GRADIENT_COLORS}
            style={styles.linearGradient}
          />
        </ImageBackground>
      ) : (
        <View style={[styles.image, styles.defaultImageContainer]}>
          <DefaultIcon size={200} color={theme.graphics.hugo[400]} />
          <Gradient
            start={{x: 0, y: 0.7}}
            end={{x: 0, y: 1}}
            colors={GRADIENT_COLORS}
            style={[styles.linearGradient, styles.absoluteGradient]}
          />
        </View>
      )}
    </Animated.View>
  );
}

export default AnimatedHeader;
