import React, {useCallback, useState} from 'react';
import {View} from 'react-native';
import {useDispatch} from 'react-redux';
import {Reactions} from '@components';
import {Reaction} from '@interfaces/reaction';
import {openReactionPicker} from '@modules/app/redux';
import {Post} from '@modules/post/interfaces';
import ReactionsSummaryPosts from '@modules/post/components/ReactionsSummaryPosts';

import {styles} from './styles';

export interface PostReactionsProps {
  reactions: Reaction[];
  post: Pick<Post, 'id'>;
  postId?: number;
  articleId?: number;
  handleReaction: (reaction: string) => void;
  onReactionPickerPress?: (reaction: string) => void;
  groupId?: number;
  isMarketplace?: boolean;
  disabled?: boolean;
}

export function PostReactions({
  reactions,
  post,
  postId,
  articleId,
  handleReaction,
  onReactionPickerPress,
  groupId,
  isMarketplace = false,
  disabled,
}: PostReactionsProps) {
  const dispatch = useDispatch();
  const [selectedReaction, setSelectedReaction] =
    useState<Nullable<string>>(null);
  const showReactionsSummary = !!selectedReaction;

  const handleToggleReactionPicker = useCallback(() => {
    dispatch(
      openReactionPicker({
        ...(articleId ? {articleId} : {postId: postId ?? post.id}),
        onReactionSelected: onReactionPickerPress,
        reactions,
        shouldUpdateLastComment: false,
        groupId,
        isMarketplace,
      }),
    );
  }, [
    articleId,
    dispatch,
    groupId,
    isMarketplace,
    onReactionPickerPress,
    post.id,
    postId,
    reactions,
  ]);

  const onToggleReactionsListDrawer = (reaction: string) =>
    setSelectedReaction(reaction);

  const onCloseReactionsSummary = () => setSelectedReaction(null);

  return (
    <>
      <View style={styles.reactionsContainer}>
        <Reactions
          onToggleReactionsBottomSheet={handleToggleReactionPicker}
          onToggleReactionsListDrawer={onToggleReactionsListDrawer}
          reactions={reactions}
          onReactionPress={handleReaction}
          disabled={disabled}
        />
      </View>
      {showReactionsSummary && (
        <ReactionsSummaryPosts
          id={postId || post.id}
          selectedReaction={selectedReaction}
          showReactionsSummary
          setSelectedReaction={setSelectedReaction}
          reactions={reactions}
          onCloseReactionsSummary={onCloseReactionsSummary}
          articleId={articleId}
          groupId={groupId}
          isMarketplace={isMarketplace}
        />
      )}
    </>
  );
}
