import React, {memo, useCallback, useRef} from 'react';
import {
  Keyboard,
  ListRenderItem,
  Pressable,
  StyleProp,
  View,
  ViewStyle,
} from 'react-native';
import MaskedView from '@react-native-masked-view/masked-view';
import {FlatList, Gesture, GestureDetector} from 'react-native-gesture-handler';
import {runOnJS} from 'react-native-reanimated';
import {Avatar, Gradient, Typography} from '@components';
import {Comment} from '@interfaces/comments';
import {StreamComment} from '@modules/livestream/interfaces';
import {useGetStreamComments} from '@modules/livestream/hooks';
import {getCompleteName} from '@shared/utils';
import {useTheme} from '@shared/theme';
import {commonStyles} from '@shared/styles';

import {GRADIENT_COLORS, styles} from './styles';

const keyExtractor = (item: StreamComment) => `${item.id}`;

interface Props {
  style?: StyleProp<ViewStyle>;
  onTap?: () => void;
}

function StreamCommentsComponent({style, onTap}: Props) {
  const flatListRef = useRef<Nullable<FlatList>>(null);
  const {theme} = useTheme();
  const {comments} = useGetStreamComments();

  const renderItem: ListRenderItem<Comment> = useCallback(
    ({item}) => {
      const name = getCompleteName(item.user);
      return (
        <View style={styles.itemContainer}>
          <Avatar
            name={name}
            url={item.user.profilePicture}
            size="sm"
            appearance="dark"
            variant="primary"
          />
          <View style={styles.itemBox}>
            <Typography variant="xxs" weight="semiBold" color={theme.white}>
              {name}
            </Typography>
            <Typography variant="xxs" color={theme.white}>
              {item.body}
            </Typography>
          </View>
        </View>
      );
    },
    [theme],
  );

  const onSingleTapEvent = () => {
    onTap && onTap();
  };

  const onTapGesture = Gesture.Tap()
    .onEnd(() => {
      runOnJS(onSingleTapEvent)();
    })
    .maxDuration(100)
    .numberOfTaps(1);

  return (
    <GestureDetector gesture={onTapGesture}>
      <View style={[commonStyles.flex, style]}>
        <View style={styles.bottomContent}>
          <MaskedView
            style={styles.commentsContainer}
            maskElement={
              <Gradient colors={GRADIENT_COLORS} style={commonStyles.flex} />
            }>
            <FlatList
              ref={flatListRef}
              data={comments}
              renderItem={renderItem}
              keyExtractor={keyExtractor}
              showsVerticalScrollIndicator={false}
              scrollEnabled
              bounces
              inverted
              style={styles.listContainer}
              contentContainerStyle={styles.listContent}
            />
          </MaskedView>
          <Pressable onPress={Keyboard.dismiss} style={commonStyles.flex} />
        </View>
      </View>
    </GestureDetector>
  );
}

export const StreamComments = memo(StreamCommentsComponent);
