import React, {ReactNode, useState} from 'react';
import {
  Pressable,
  View,
  LayoutAnimation,
  UIManager,
  StyleProp,
  ViewStyle,
} from 'react-native';
import Animated, {
  runOnJS,
  useAnimatedStyle,
  useSharedValue,
  withTiming,
} from 'react-native-reanimated';
import {IconArrowRight} from '@tabler/icons-react-native';
import {Typography} from '@components/_core/Typography';
import {CloseButton} from '@components/_HuGo/Button';
import {useTheme} from '@shared/theme';
import {isAndroid} from '@shared/utils';
import {commonStyles} from '@shared/styles';

import {AlertVariant} from './interfaces';
import {getVariantShape, styles} from './styles';

if (isAndroid) {
  UIManager.setLayoutAnimationEnabledExperimental?.(true);
}

export interface AlertProps {
  title: string;
  variant?: AlertVariant;
  description?: string | ReactNode;
  action?: {text: string; onPress: () => void};
  withClose?: boolean;
  onClose?: () => void;
  style?: StyleProp<ViewStyle>;
  withArrow?: boolean;
  withIcon?: boolean;
}

export function Alert({
  title,
  description,
  action,
  withClose,
  onClose,
  variant = 'info',
  style,
  withArrow,
  withIcon = true,
}: AlertProps) {
  const {theme, iconSizes} = useTheme();
  const opacity = useSharedValue(1);
  const [isVisible, setIsVisible] = useState(true);
  const {backgroundColor, borderColor, borderLeftColor, textColor, Icon} =
    getVariantShape(variant, theme);

  const onClosePress = () => {
    LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut);
    opacity.value = withTiming(0, {duration: 250}, () => {
      runOnJS(setIsVisible)(false);
      onClose && runOnJS(onClose)();
    });
  };

  const animatedStyle = useAnimatedStyle(() => ({
    opacity: opacity.value,
  }));

  return isVisible ? (
    <Animated.View
      style={[
        styles.container,
        {backgroundColor, borderColor, borderLeftColor},
        animatedStyle,
        style,
      ]}>
      {withIcon && <Icon size={iconSizes.x6} color={textColor} />}
      <View style={commonStyles.flex}>
        <Typography variant="s" weight="semiBold" color={textColor}>
          {title}
        </Typography>
        {!!description &&
          (typeof description === 'string' ? (
            <Typography variant="xs" color={textColor}>
              {description}
            </Typography>
          ) : (
            description
          ))}
      </View>
      {!!action && (
        <Pressable style={styles.actionButton} onPress={action.onPress}>
          <Typography variant="xs" weight="semiBold" color={textColor}>
            {action.text}
          </Typography>
        </Pressable>
      )}
      {withArrow && <IconArrowRight color={textColor} />}
      {withClose && <CloseButton onPress={onClosePress} size="sm" />}
    </Animated.View>
  ) : null;
}

export * from './interfaces';
