import React, { useCallback } from 'react';
import {
  Image,
  ImageStyle,
  StyleSheet,
  TouchableOpacity,
  View,
  ViewStyle,
} from 'react-native';
import {
  useStyles,
  useTheme,
  useReactionSpace,
  useReactionPacks,
  useMessageItemPopover,
} from '../../hooks';
import {
  IChatUserMessage,
  PopoverType,
  ComponentStyleProp,
  LLComponentStyleFn,
} from '../../types';
import {
  LLUserReactionCounts,
  LLUserReactionCountsProps,
} from '../LLReactionPicker';

export type LLChatMessageItemFooterStyles = {
  footerContainer: ViewStyle;
  addReactionIcon: ImageStyle;
};

export type LLChatMessageItemFooterProps =
  ComponentStyleProp<LLChatMessageItemFooterStyles> & {
    message: IChatUserMessage;
    UserReactionsCountComponent?: typeof LLUserReactionCounts;
    UserReactionsCountComponentStyles?: LLUserReactionCountsProps['styles'];
  };

export function LLChatMessageItemFooter({
  message: messageDetails,
  styles: stylesProp,
  UserReactionsCountComponentStyles,
  UserReactionsCountComponent = LLUserReactionCounts,
}: LLChatMessageItemFooterProps) {
  const messageItemFooterStyles = useStyles({
    componentStylesFn: getMessageItemFooterStyles,
    stylesProp,
  });
  const { themeAssets } = useTheme();
  const { hidePopover, showPopover, popoverDetail } = useMessageItemPopover({
    messageId: messageDetails.id,
  });
  const { reactionSpace } = useReactionSpace({
    targetGroupId: messageDetails.chat_room_id,
  });
  const { reactionPacks } = useReactionPacks({
    reactionSpaceId: reactionSpace?.id,
  });
  const onShowReactionPicker = useCallback(() => {
    showPopover({
      messageId: messageDetails.id,
      popoverType: PopoverType.Reactions,
    });
  }, []);
  const isDeletedMessage = !!messageDetails.isDeleted;

  if (isDeletedMessage || !reactionPacks.length || !reactionSpace) {
    return null;
  }

  return (
    <View style={messageItemFooterStyles.footerContainer}>
      <TouchableOpacity
        onPress={onShowReactionPicker}
        accessibilityLabel="Show reactions picker"
      >
        <Image
          style={messageItemFooterStyles.addReactionIcon}
          source={themeAssets.reaction}
        />
      </TouchableOpacity>
      <UserReactionsCountComponent
        targetGroupId={messageDetails.chat_room_id}
        targetId={messageDetails.id}
        showReactionPicker={
          popoverDetail && popoverDetail.popoverType === PopoverType.Reactions
        }
        onReactionItemPress={hidePopover}
        styles={UserReactionsCountComponentStyles}
      />
    </View>
  );
}

const getMessageItemFooterStyles: LLComponentStyleFn<LLChatMessageItemFooterStyles> =
  ({ theme }) =>
    StyleSheet.create({
      footerContainer: {
        flexDirection: 'row',
        alignItems: 'flex-start',
        marginTop: 10,
      },
      addReactionIcon: {
        height: 22,
        width: 22,
        marginTop: 2,
        marginBottom: 6,
      },
    });
