import React, {useState} from 'react';
import {View} from 'react-native';
import {shallowEqual, useDispatch} from 'react-redux';
import {useNavigation} from '@react-navigation/native';
import {Reactions, Pressable, ReactionsSummaryBottomSheet} from '@components';
import {Acknowledgement as AcknowledgementType} from '@modules/acknowledgement/interfaces';
import ContentActionsDialog, {
  ContentType,
} from '@modules/acknowledgement/components/ContentActionsDialog';
import {openReactionPicker} from '@modules/app/redux';
import {useGetUserFromReactionAcknowledgement} from '@modules/acknowledgement/hooks/useGetUserFromReactionAcknowledgement';
import {useAppSelector} from '@redux/utils';
import {DEFAULT_REACTION, Screens} from '@shared/constants';
import {useTheme} from '@shared/theme';

import AvatarWithName from './components/AvatarWithName';
import AcknowledgementBody, {
  AcknowledgementBodyProps,
} from './components/AcknowledgementBody';
import AcknowledgementComment from './components/AcknowledgementComment';
import {styles} from './styles';

interface Props extends Pick<AcknowledgementBodyProps, 'onPress'> {
  acknowledgement: AcknowledgementType;
  canManageRecognitions?: boolean;
  displayLastComment?: boolean;
  commentCount?: number;
  onReactionPress?: (reaction: string) => void;
  externalUserId?: number;
}

function Acknowledgement({
  acknowledgement,
  onPress,
  displayLastComment,
  canManageRecognitions,
  commentCount,
  onReactionPress,
  externalUserId,
}: Props) {
  const [showDialog, setShowDialog] = useState(false);
  const [selectedReaction, setSelectedReaction] = useState<Nullable<string>>(
    acknowledgement.reactions?.[0]?.emoji || DEFAULT_REACTION,
  );
  const [showReactionsSummary, setShowReactionsSummary] = useState(false);
  const dispatch = useDispatch();
  const {theme} = useTheme();
  const navigation = useNavigation();
  const {canReact, userId} = useAppSelector(
    ({user}) => ({
      userId: user.id,
      canReact:
        user.permissions.CAN_REACT_CONTENT ||
        user.permissions.CAN_REACT_ACKNOWLEDGEMENTS,
    }),
    shallowEqual,
  );
  const acknowledgmentsCanBeCommented = useAppSelector(
    ({instance}) => instance.acknowledgmentsCanBeCommented,
  );
  const {
    id,
    createdAt,
    attachments,
    acknowledger,
    acknowledged,
    acknowledgeds,
    body,
    category,
    reactions,
    points,
    pointsVisible,
  } = acknowledgement;

  const handlePressComment = () =>
    navigation.navigate(Screens.ACKNOWLEDGEMENT_DETAIL, {
      id,
      shouldScrollToComments: true,
      isAcknowledgement: true,
    });

  const onAvatarPress = () =>
    !acknowledger.deleted &&
    navigation.navigate(Screens.PROFILE, {userId: acknowledger.id});

  const onToggleReactionsBottomSheet = () =>
    dispatch(
      openReactionPicker({
        postId: id,
        ack: true,
        reactions,
        ...(externalUserId && {userId: externalUserId}),
      }),
    );

  const onPressOption = () => setShowDialog(true);

  const onHideDialog = () => setShowDialog(false);

  const onToggleReactionsListDrawer = (reaction: string) => {
    setSelectedReaction(reaction);
    setShowReactionsSummary(true);
  };

  const onCloseReactionsSummary = () => {
    setShowReactionsSummary(false);
  };

  const queryData = useGetUserFromReactionAcknowledgement({
    acknowledgementId: id,
    reaction: selectedReaction,
    reactions,
    canReact,
  });

  const onSelectReaction = (reaction: string) => {
    setSelectedReaction(reaction);
  };

  return (
    <>
      <View
        style={[
          styles.acknowledgementCardContainer,
          {backgroundColor: theme.background.layout.tertiary},
        ]}>
        <Pressable style={styles.pressableButton} onPress={onAvatarPress}>
          <AvatarWithName
            onPressOption={onPressOption}
            canManagePosts={canManageRecognitions || acknowledger.id === userId}
            acknowledger={acknowledger}
            createdAt={createdAt}
          />
        </Pressable>
        <AcknowledgementBody
          acknowledged={acknowledged}
          acknowledgeds={acknowledgeds}
          category={category}
          {...(pointsVisible && {points})}
          attachments={attachments}
          body={body}
          onPress={onPress}
        />
        {canReact && (
          <View style={styles.commentsContainer}>
            <Reactions
              onToggleReactionsBottomSheet={onToggleReactionsBottomSheet}
              onToggleReactionsListDrawer={onToggleReactionsListDrawer}
              reactions={reactions}
              onReactionPress={onReactionPress}
            />
          </View>
        )}
        <AcknowledgementComment
          acknowledgementId={id}
          lastComment={acknowledgement.lastComments?.[0]}
          commentCount={commentCount}
          onPressToComments={handlePressComment}
          displayLastComment={displayLastComment}
          canComment={acknowledgmentsCanBeCommented}
        />
      </View>
      <ContentActionsDialog
        isVisible={showDialog}
        isOwner={userId === acknowledger.id}
        contentType={ContentType.ACKNOWLEDGEMENT}
        onHide={onHideDialog}
        acknowledgementId={id}
        body={body}
        attachments={attachments}
        acknowledgeds={acknowledgeds}
      />
      {showReactionsSummary && canReact && (
        <ReactionsSummaryBottomSheet
          visible={showReactionsSummary}
          selectedReaction={selectedReaction}
          setSelectedReaction={onSelectReaction}
          reactions={reactions}
          queryData={queryData}
          onClose={onCloseReactionsSummary}
        />
      )}
    </>
  );
}

export default Acknowledgement;
