import React, {useCallback, useState} from 'react';
import {useTranslation} from 'react-i18next';
import {Pressable, Typography} from '@components';
import {Comment as CommentType} from '@interfaces/comments';
import {usePermissions, useUserId} from '@redux/selectors';
import {useTheme} from '@shared/theme';
import {Comment} from '@shared/components';

import ContentActionsDialog from '../ContentActionsDialog';
import {styles} from './styles';

interface CommentItemProps {
  postId: number;
  groupId?: number;
  isGroupAdmin?: boolean;
  articleId?: number;
  isMarketplace?: boolean;
  item: CommentType;
  canInteract?: boolean;
  onTagPress: (targetId: number) => void;
  onReplyPress: () => void;
  onDetailPress: () => void;
  toggleReactionsBottomSheet: (comment: CommentType) => void;
  onToggleReactionsListDrawer: (comment: CommentType, reaction: string) => void;
  onReactionPress: (reaction: string, comment: CommentType) => void;
  isArchived?: boolean;
  showOptions?: boolean;
}

// TODO: all conditions on groupId, articleId and isMarketplace should be handled outside this component
export function CommentItem({
  postId,
  groupId,
  articleId,
  isMarketplace,
  item,
  onTagPress,
  onReplyPress,
  onDetailPress,
  toggleReactionsBottomSheet,
  onReactionPress,
  onToggleReactionsListDrawer,
  isGroupAdmin,
  canInteract,
  isArchived,
  showOptions = true,
}: CommentItemProps) {
  const {theme} = useTheme();
  const {t} = useTranslation();
  const [selectedComment, setSelectedComment] =
    useState<Nullable<CommentType>>(null);
  const firstChild = item.children?.[0];
  const {
    MANAGE_COMMENTS,
    MANAGE_ARTICLES_COMMENTS,
    MANAGE_FEED_COMMENTS,
    MANAGE_MARKETPLACE_COMMENTS,
    CAN_REACT_CONTENT,
    CAN_REACT_POSTS,
    CAN_REACT_ARTICLES,
    CAN_REACT_MARKETPLACE_POSTS,
  } = usePermissions();
  const canReact =
    CAN_REACT_CONTENT ||
    (groupId && canInteract) ||
    (articleId && CAN_REACT_ARTICLES) ||
    (isMarketplace && CAN_REACT_MARKETPLACE_POSTS) ||
    (!articleId && !isMarketplace && CAN_REACT_POSTS);
  const isAdmin =
    (groupId && isGroupAdmin) ||
    (MANAGE_COMMENTS && (!groupId || isGroupAdmin)) ||
    (articleId && MANAGE_ARTICLES_COMMENTS) ||
    (isMarketplace && MANAGE_MARKETPLACE_COMMENTS) ||
    (!isMarketplace && !articleId && !groupId && MANAGE_FEED_COMMENTS);
  const currentUserId = useUserId();

  const onToggleReactionsBottomSheet = useCallback(
    () => toggleReactionsBottomSheet(item),
    [toggleReactionsBottomSheet, item],
  );
  const onHandleReactionPress = useCallback(
    (reaction: string) => onReactionPress(reaction, item),
    [onReactionPress, item],
  );

  const onToggleFirtsChildReactionsBottomSheet = useCallback(
    () => toggleReactionsBottomSheet(firstChild),
    [toggleReactionsBottomSheet, firstChild],
  );
  const onHandleFirstChildReactionPress = useCallback(
    (reaction: string) => onReactionPress(reaction, firstChild),
    [onReactionPress, firstChild],
  );

  const onPressUser = useCallback(
    (targetUserId: number) => () => onTagPress(targetUserId),
    [onTagPress],
  );

  const showCommentOptions = (comment: CommentType) => () => {
    setSelectedComment(comment);
  };

  const hideCommentOptions = () => setSelectedComment(null);

  const onPressReactionsListDrawer = useCallback(
    (reaction: string) => onToggleReactionsListDrawer(item, reaction),
    [onToggleReactionsListDrawer, item],
  );
  const onPressFirstChildReactionsListDrawer = useCallback(
    (reaction: string) => onToggleReactionsListDrawer(firstChild, reaction),
    [onToggleReactionsListDrawer, firstChild],
  );

  return (
    <>
      <Comment
        canReact={canReact}
        containerStyle={styles.comment}
        firstName={item.user?.firstName}
        lastName={item.user?.lastName}
        isExternal={item.isExternal}
        avatar={item.user?.profilePicture}
        comment={item.body}
        createAt={item.createdAt}
        multimediaAttachments={item.attachments}
        bodyAttributes={item.bodyAttributes}
        onPressUser={onPressUser(item.user?.id)}
        onTagPress={onTagPress}
        onReactionPress={onHandleReactionPress}
        showOptions={
          showOptions &&
          !isArchived &&
          (currentUserId === item.user?.id || isAdmin)
        }
        reactions={item.reactions || []}
        onPressLeftIcon={showCommentOptions(item)}
        onToggleReactionsBottomSheet={onToggleReactionsBottomSheet}
        onToggleReactionsListDrawer={onPressReactionsListDrawer}
        isArchived={isArchived}
      />
      <Pressable onPress={onReplyPress} style={styles.replyContainer}>
        <Typography
          weight="semiBold"
          variant="xs"
          color={theme.text.neutral.brand}>
          {t('general.reply')}
        </Typography>
      </Pressable>
      {item.childrenNumber > 1 && (
        <Pressable onPress={onDetailPress}>
          <Typography
            color={theme.text.neutral.brand}
            weight="semiBold"
            variant="xs"
            style={styles.showMoreReplies}>
            {t('acknowledgements.show_replies', {
              count: item.childrenNumber - 1,
            })}
          </Typography>
        </Pressable>
      )}
      {firstChild && (
        <Comment
          containerStyle={[styles.comment, styles.marginBottom]}
          firstName={firstChild.user?.firstName}
          lastName={firstChild.user?.lastName}
          isExternal={firstChild.isExternal}
          onPressUser={onPressUser(firstChild.user?.id)}
          avatar={firstChild.user?.profilePicture}
          comment={firstChild.body}
          reactions={firstChild.reactions}
          onReactionPress={onHandleFirstChildReactionPress}
          createAt={firstChild.createdAt}
          showOptions={
            showOptions &&
            !isArchived &&
            (currentUserId === firstChild.user.id || isAdmin)
          }
          onPressLeftIcon={showCommentOptions(firstChild)}
          bodyAttributes={firstChild.bodyAttributes}
          isReply
          onTagPress={onTagPress}
          multimediaAttachments={firstChild.attachments}
          onToggleReactionsBottomSheet={onToggleFirtsChildReactionsBottomSheet}
          onToggleReactionsListDrawer={onPressFirstChildReactionsListDrawer}
          isArchived={isArchived}
        />
      )}
      <ContentActionsDialog
        isVisible={!!selectedComment}
        isOwner={currentUserId === selectedComment?.user.id}
        comment={selectedComment}
        onHide={hideCommentOptions}
        postId={postId}
        groupId={groupId}
        isMarketplace={isMarketplace}
      />
    </>
  );
}
