import React, {
  forwardRef,
  memo,
  RefObject,
  useCallback,
  useRef,
  useState,
} from 'react';
import {
  Pressable,
  ScrollView,
  StyleProp,
  TextInput,
  View,
  ViewStyle,
} from 'react-native';
import {useTranslation} from 'react-i18next';
import {shallowEqual} from 'react-redux';
import {IconSend} from '@tabler/icons-react-native';
import {IconButton} from '@components';
import {useStreamPostInteraction} from '@modules/livestream/hooks';
import {useAppSelector} from '@redux/utils';
import {DARK_THEME} from '@shared/theme';

import {ReactionButton} from './components/ReactionButton';
import {styles} from './styles';

const STREAM_REACTIONS = ['👍', '❤️', '🥰', '😂', '😮', '😢', '😡'];

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

const CommentInputComponent = forwardRef<TextInput, Props>(
  ({style, onFocus, onBlur}, forwardedRef) => {
    const {t} = useTranslation();
    const localRef = useRef<TextInput>(null);
    const [isLoading, setIsLoading] = useState(false);
    const {
      canCommentGeneral,
      canCommentInPosts,
      canReact,
      postId,
      isPostCommentsEnabled,
    } = useAppSelector(
      ({user, livestream}) => ({
        isPostCommentsEnabled: !!livestream.post.data?.commentsEnabled,
        canCommentGeneral: user.permissions.CREATE_COMMENT,
        canCommentInPosts: user.permissions.CREATE_COMMENT_IN_POSTS,
        canReact:
          user.permissions.CAN_REACT_CONTENT ||
          user.permissions.CAN_REACT_POSTS,
        postId: livestream.post.data?.id,
      }),
      shallowEqual,
    );
    const canComment = canCommentGeneral || canCommentInPosts;
    const [inputComment, setInputComment] = useState('');
    const showSendButton = !!inputComment.trim().length;
    const ref = (forwardedRef || localRef) as RefObject<TextInput>;
    const {createCommentHandler} = useStreamPostInteraction();
    const onChangeText = useCallback((newValue: string) => {
      setInputComment(newValue);
    }, []);

    const onSubmitComment = async () => {
      const body = inputComment.trim();
      if (body && !isLoading) {
        setInputComment('');
        setIsLoading(true);
        try {
          await createCommentHandler(body);
        } finally {
          setIsLoading(false);
        }
      }
    };

    const onInputContainerPress = () => {
      ref.current?.focus();
    };

    return isPostCommentsEnabled ? (
      <View style={[styles.container, style]}>
        <ScrollView
          horizontal
          bounces={false}
          alwaysBounceHorizontal={false}
          showsHorizontalScrollIndicator={false}
          contentContainerStyle={styles.scrollView}
          keyboardShouldPersistTaps="handled">
          {canComment && (
            <Pressable
              onPress={onInputContainerPress}
              style={[
                styles.inputContainer,
                canReact && styles.inputWithReactions,
              ]}>
              <TextInput
                ref={ref}
                value={inputComment}
                onChangeText={onChangeText}
                onFocus={onFocus}
                onBlur={onBlur}
                style={styles.commentInput}
                placeholderTextColor={DARK_THEME.neutralTextInverted}
                placeholder={t('general.write_comment')}
                multiline
                editable={!!postId}
              />
              {showSendButton && (
                <IconButton
                  disabled={isLoading}
                  Icon={IconSend}
                  onPress={onSubmitComment}
                />
              )}
            </Pressable>
          )}
          {canReact
            ? STREAM_REACTIONS.map(reaction => (
                <ReactionButton key={reaction} reaction={reaction} />
              ))
            : null}
        </ScrollView>
      </View>
    ) : null;
  },
);

export {COMMENT_INPUT_HEIGHT} from './styles';
export const CommentInput = memo(CommentInputComponent);
