//TODO: Add translations for accesibility labels
import React, {memo, useEffect, useMemo} from 'react';
import {StyleSheet, View} from 'react-native';
import {useTranslation} from 'react-i18next';
import {IconFile, IconX} from '@tabler/icons-react-native';
import Animated, {
  interpolate,
  useAnimatedStyle,
  useSharedValue,
  withTiming,
} from 'react-native-reanimated';
import {Avatar, IconButton, Image, Typography} from '@components';
import {IconPlayVideo} from '@modules/chats/components';
import {usePrefixIconAndText} from '@modules/chats/hooks';
import {useMessageActionsContext} from '@modules/chats/contexts';
import {getChatImage, getPreviewAsset} from '@modules/chats/utils';
import {IMAGE_SIZE_TINY_PX} from '@modules/chats/constants';
import {BORDER_RADIUS, SPACING, useTheme} from '@shared/theme';

import {useChatAnimations} from '../ChatFooter/components/AnimationProvider';

const REGEX_NEW_LINE = /\n/g;

interface Props {
  isVisible: boolean;
}

const borderRadius = BORDER_RADIUS.l;

function ChatReplyComponent({isVisible}: Props) {
  const {t} = useTranslation();
  const {theme, iconSizes} = useTheme();
  const {dialog} = useChatAnimations();
  const heightSharedValue = useSharedValue(0);
  const {targetMessage, reset, isReplying} = useMessageActionsContext();
  const {showPreview, attachment, isFile} = getPreviewAsset({
    assets: targetMessage?.data.attachments,
  });
  const {PrefixIcon, defaultText} = usePrefixIconAndText({
    assets: targetMessage?.data.attachments,
  });
  const formattedText = useMemo(
    () =>
      targetMessage?.data.formatted_text?.replace(REGEX_NEW_LINE, ' ') ||
      defaultText,
    [defaultText, targetMessage?.data.formatted_text],
  );
  const accessibilityLabel = useMemo(() => {
    const senderName = targetMessage?.isSentByCurrentUser
      ? t('chat.you')
      : targetMessage?.data.username;
    return `Reply to, ${senderName}, ${formattedText}`;
  }, [
    t,
    targetMessage?.isSentByCurrentUser,
    targetMessage?.data.username,
    formattedText,
  ]);

  const animatedStyle = useAnimatedStyle(() => {
    if (!_WORKLET) {
      return {
        borderTopLeftRadius: borderRadius,
        borderTopRightRadius: borderRadius,
        height: 0,
      };
    }

    const radius = dialog
      ? interpolate(dialog.value, [0, 1], [borderRadius, 0])
      : borderRadius;
    return {
      borderTopLeftRadius: radius,
      borderTopRightRadius: radius,
      height: heightSharedValue.value,
    };
  }, []);

  useEffect(() => {
    if (isVisible) {
      heightSharedValue.value = withTiming(72, {duration: 250});
    } else {
      // to avoid on mount
      if (heightSharedValue.value > 0) {
        heightSharedValue.value = withTiming(0, {duration: 150});
      }
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isVisible]);

  const containerStyle = useMemo(() => {
    return [{backgroundColor: theme.background.layout.tertiary}, animatedStyle];
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [theme.background.layout.tertiary]);

  return (
    <Animated.View style={containerStyle}>
      {!targetMessage || !isReplying ? null : (
        <View style={styles.container}>
          <View
            style={styles.content}
            accessible={true}
            accessibilityRole="text"
            accessibilityLabel={accessibilityLabel}>
            <Typography variant="xs" weight="semiBold">
              {targetMessage.isSentByCurrentUser
                ? t('chat.you')
                : targetMessage.data.username}
            </Typography>
            <View style={styles.textContainer}>
              {PrefixIcon && (
                <PrefixIcon
                  size={iconSizes.x3}
                  color={theme.text.neutral.lighter}
                />
              )}
              <Typography
                variant="xxs"
                color={theme.text.neutral.lighter}
                style={styles.text}
                numberOfLines={1}>
                {formattedText}
              </Typography>
            </View>
          </View>
          {showPreview && (
            <View style={styles.previewContainer}>
              <Image
                // Both image and video preview URLs hit our authenticated
                // asset endpoints — the Image wrapper only injects the
                // header for http URIs, so a local file:// is unaffected.
                withAuthHeader
                enableCache
                timeout={15_000}
                source={{
                  uri: getChatImage.addSize(
                    attachment.isVideo
                      ? attachment.thumbnailUrl
                      : attachment.url,
                    IMAGE_SIZE_TINY_PX,
                  ),
                }}
                style={[
                  styles.imagePreview,
                  {backgroundColor: theme.text.neutral.default},
                ]}
              />
              {attachment.isVideo && <IconPlayVideo size="sm" />}
            </View>
          )}
          {isFile && <Avatar Icon={IconFile} variant="primary" />}
          <IconButton
            Icon={IconX}
            variant="flat"
            iconColor={theme.text.neutral.default}
            onPress={reset}
            accessible={true}
            accessibilityRole="button"
            accessibilityLabel="Cancel reply"
            accessibilityHint="Tap to cancel the reply"
          />
        </View>
      )}
    </Animated.View>
  );
}

export const ChatReply = memo(ChatReplyComponent);

const styles = StyleSheet.create({
  container: {
    flexDirection: 'row',
    alignItems: 'center',
    padding: SPACING.x2,
    gap: SPACING['x0.5'],
  },
  roundedContainer: {
    borderTopLeftRadius: BORDER_RADIUS.l,
    borderTopRightRadius: BORDER_RADIUS.l,
  },
  content: {
    flex: 1,
    flexDirection: 'column',
  },
  textContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: SPACING['x0.5'],
  },
  text: {
    flex: 1,
    marginRight: SPACING['x0.5'],
  },
  imagePreview: {
    alignItems: 'center',
    borderRadius: BORDER_RADIUS.s,
    height: 40,
    justifyContent: 'center',
    width: 40,
  },
  previewContainer: {
    alignItems: 'center',
    justifyContent: 'center',
  },
});
