import React, {useMemo} from 'react';
import {View} from 'react-native';
import {
  HtmlRender,
  getBodyNews,
  Image,
  Typography,
  Pill,
  FilesCarousel,
  CommentFooter,
} from '@components';
import PostReactions from '@components/Post/components/PostBody/components/PostReactions';
import {Attachment} from '@interfaces/attachments';
import {Article} from '@modules/article/interfaces';
import {useToggleArticleReaction} from '@modules/article/hooks/useToggleArticleReaction';
import {useTheme} from '@shared/theme';

import {styles} from './styles';

interface Props {
  contentWidth: number;
  article: Article;
  showReactions: boolean;
  timeAgo?: string;
  onLoaded?: () => void;
  onPressComment: () => void;
  showAddComment: boolean;
}

export function ArticleBody({
  contentWidth,
  article,
  timeAgo,
  showReactions,
  onLoaded,
  onPressComment,
  showAddComment,
}: Props) {
  const {theme} = useTheme();
  const html = useMemo(
    () =>
      getBodyNews({
        content: article,
        backgroundColor: theme.background.elements.default,
      }),
    [article, theme.background.elements.default],
  );

  const {toggleReaction} = useToggleArticleReaction(
    article.reactions,
    article.id,
  );

  const handleNoticeReaction = (reaction: string) => toggleReaction(reaction);

  return (
    <>
      <Image source={{uri: article.coverPicture}} style={styles.imageStyle} />
      <View style={styles.titleContainer}>
        <Typography variant="m" weight="semiBold">
          {article.title}
        </Typography>
        {timeAgo && (
          <Typography
            variant="xs"
            color={theme.text.neutral.lighter}
            style={styles.timeAgo}>
            {timeAgo}
          </Typography>
        )}
        {!!article.topics?.length && (
          <View style={styles.topicContainer}>
            {article.topics.map(topic => (
              <Pill key={topic.id} text={topic.name} variant="neutral" />
            ))}
          </View>
        )}
      </View>
      <HtmlRender
        contentWidth={contentWidth}
        html={html}
        onLoaded={onLoaded}
        withZoom
      />
      <FilesCarousel
        files={(article.attachments || []) as Attachment[]}
        style={styles.filesCarousel}
      />
      {showReactions && (
        <PostReactions
          reactions={article.reactions}
          post={article}
          handleReaction={handleNoticeReaction}
          articleId={article.id}
        />
      )}
      {showAddComment && (
        <CommentFooter
          onPressFooter={onPressComment}
          commentCount={article.commentCount}
          canAnswerComment={showAddComment}
        />
      )}
    </>
  );
}
