import React, {useCallback} from 'react';
import {Image, View, Pressable} from 'react-native';
import Animated, {
  useAnimatedStyle,
  useSharedValue,
  withTiming,
} from 'react-native-reanimated';
import * as Haptics from 'expo-haptics';
import {IconX} from '@tabler/icons-react-native';
import {Spinner} from '@components/_HuGo';
import {Video} from '@components/_core/Video';
import {Attachment, AttachmentType} from '@interfaces/attachments';
import {ICON_SIZES, useTheme} from '@shared/theme';

import {styles} from './styles';

interface PreviewProps extends Attachment {
  onDelete?: () => void;
  drag?: () => void;
}

const PreviewAttachment = ({
  path,
  thumbnailUrl,
  isLoading,
  onDelete,
  type,
  url,
  drag,
  ...rest
}: PreviewProps) => {
  const {theme} = useTheme();
  const isVideo = type === AttachmentType.VIDEO;
  const pressed = useSharedValue(0);

  const onPressOut = useCallback(() => {
    pressed.value = withTiming(0, {duration: 150});
  }, [pressed]);

  const onLongPress = useCallback(() => {
    pressed.value = withTiming(1, {duration: 100});
    Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light);
    drag?.();
  }, [drag, pressed]);

  const animatedStyle = useAnimatedStyle(() => ({
    transform: [{scale: pressed.value ? 0.94 : 1}],
    opacity: pressed.value ? 0.9 : 1,
  }));

  const videoProps = {
    style: styles.image,
    withSmallPlayButton: true,
    video: {
      path,
      thumbnailUrl,
      isLoading,
      type,
      url,
      ...rest,
    },
  };
  return (
    <Pressable
      onLongPress={onLongPress}
      delayLongPress={300}
      disabled={!drag}
      onPressOut={onPressOut}
      style={styles.container}>
      <Animated.View style={animatedStyle}>
        {isVideo ? (
          drag ? (
            <View pointerEvents="none">
              <Video {...videoProps} />
            </View>
          ) : (
            <Video {...videoProps} />
          )
        ) : (
          <Image style={styles.image} source={{uri: path || url || ''}} />
        )}
        {isLoading ? (
          <View
            style={[
              styles.overlay,
              {backgroundColor: theme.action.background.neutral.hover},
            ]}>
            <Spinner />
          </View>
        ) : (
          onDelete && (
            <Pressable
              onPress={onDelete}
              style={[
                styles.deleteButtonContainer,
                {backgroundColor: theme.action.background.neutral.hover},
              ]}>
              <IconX size={ICON_SIZES.x4} color={theme.icon.neutral.default} />
            </Pressable>
          )
        )}
      </Animated.View>
    </Pressable>
  );
};

export default PreviewAttachment;
