import React, {ForwardedRef, forwardRef, useCallback} from 'react';
import {View} from 'react-native';
import {useTranslation} from 'react-i18next';
import {
  addTaggedUser,
  changeTaggedUserStartPosition,
  deleteTaggedUser,
} from 'tag-users';
import {RichText} from '@10play/tentap-editor';
import {User} from '@interfaces/user';
import {useTheme} from '@shared/theme';
import {isIos} from '@shared/utils';

import {BODY_MAX_LENGTH} from '../../constants';
import TagUsersTextInput from '../TagUsersTextInput';
import {useNewPost} from '../../hooks/useNewPost';
import {styles} from './styles';

interface Props {
  groupId?: number;
}

function RichTextInput({groupId}: Props, richTextRef: ForwardedRef<View>) {
  const {
    editor,
    post,
    hasPoll,
    messageBody,
    setMessageBody,
    messageBodyWithoutLastTag,
    setMessageBodyWithoutLastTag,
    taggedUsers,
    setTaggedUsers,
  } = useNewPost();
  const {t} = useTranslation();
  const {theme} = useTheme();

  const showRichTextInput = Boolean(!post?.body || post.bodyHtml);

  const onChangeTaggedUserStartPosition = useCallback(
    (userId: number, newStartPosition: number) =>
      setTaggedUsers(prevState =>
        changeTaggedUserStartPosition(prevState, userId, newStartPosition),
      ),
    [setTaggedUsers],
  );

  const onAddTaggedUser = useCallback(
    (user: User) => setTaggedUsers(prevState => addTaggedUser(prevState, user)),
    [setTaggedUsers],
  );

  const onDeleteTaggedUser = useCallback(
    (userId: number) =>
      setTaggedUsers(prevState => deleteTaggedUser(prevState, userId)),
    [setTaggedUsers],
  );

  return showRichTextInput ? (
    <View style={styles.container}>
      <View style={styles.richText} ref={richTextRef}>
        <RichText editor={editor} showsVerticalScrollIndicator={false} />
      </View>
    </View>
  ) : (
    <TagUsersTextInput
      placeholder={t(
        hasPoll ? 'post.make_question' : 'general.write_something',
      )}
      placeholderTextColor={theme.text.neutral.lighter}
      maxLength={BODY_MAX_LENGTH}
      style={[styles.input, {color: theme.text.neutral.default}]}
      value={messageBody || ''}
      messageBodyWithoutLastTag={messageBodyWithoutLastTag}
      setMessageBodyWithoutLastTag={setMessageBodyWithoutLastTag}
      multiline
      groupId={groupId}
      // `scrollEnabled` is true in iOS to prevent the text input from scrolling down when user enters some text
      scrollEnabled={isIos}
      borderBottomWidth={0}
      onChangeText={setMessageBody}
      taggedUsers={taggedUsers}
      changeTaggedUserStartPosition={onChangeTaggedUserStartPosition}
      addTaggedUser={onAddTaggedUser}
      deleteTaggedUser={onDeleteTaggedUser}
      autoCorrect
      autoCapitalize
      autoFocus
    />
  );
}

export default forwardRef(RichTextInput);
