import { type FC, useMemo } from 'react';
import { Link as RouterLink } from 'react-router-dom';

import Box from '@material-hu/mui/Box';
import Stack from '@material-hu/mui/Stack';

import { usePostAttachments } from 'src/hooks/usePostAttachments';
import { feedRoutes } from 'src/pages/dashboard/feed/routes';
import { groupsRoutes } from 'src/pages/dashboard/groups/routes';
import { type GroupPost } from 'src/types/groups';
import { type Post, PostType } from 'src/types/posts';

import PostBody from '../PostBody';
import { PostCardFeatures } from '../PostCardFeatures';
import PostCardHeader from '../PostCardHeader';

const MAX_CHARACTERS_LIMIT = 250;
const MAX_NEW_LINES_LIMIT = 4;

type SharedPostEmbeddedProps = {
  post: Post | GroupPost;
};

export const SharedPostEmbedded: FC<SharedPostEmbeddedProps> = ({ post }) => {
  const { mediaList, fileList, gif } = usePostAttachments(
    post.attachments ?? [],
  );

  const groupId = useMemo(() => {
    if (post.type === PostType.GroupType) return post.groupId;
    return post.group?.id ?? undefined;
  }, [post]);

  const detailLink = useMemo(
    () =>
      groupId !== undefined
        ? groupsRoutes.post.detail(groupId, post.id)
        : feedRoutes.post.detail(post.id),
    [post.id, groupId],
  );

  const containerId = `shared-post-embedded-${post.id}`;

  return (
    <Box
      id={containerId}
      sx={{ px: 2 }}
    >
      <Stack
        component={RouterLink}
        to={detailLink}
        sx={{
          cursor: 'pointer',
          color: 'inherit',
          textDecoration: 'none',
          borderRadius: theme => theme.shape.borderRadiusL,
          border: theme =>
            `1px solid ${theme.palette.new.border.neutral.default}`,
          overflow: 'hidden',
          backgroundColor: theme =>
            theme.palette.new.background.elements.default,
        }}
      >
        <PostCardHeader
          user={post.user}
          publicationDatetime={post.publicationDatetime}
          updatedAt={post.updatedAt}
          createdAt={post.createdAt}
          isExternal={post.isExternal}
          hideKeyUpdateHeader
        />
        <Stack sx={{ pb: 2, gap: 2 }}>
          <Box sx={{ px: 2 }}>
            <PostBody
              bodyHtml={post.bodyHtml}
              body={post.body}
              bodyAttributes={post.bodyAttributes}
              maxCharacters={MAX_CHARACTERS_LIMIT}
              maxNewLines={MAX_NEW_LINES_LIMIT}
            />
          </Box>
          <PostCardFeatures
            id={post.id}
            mediaList={mediaList}
            fileList={fileList}
            linkPreviews={post.linkPreviews}
            poll={post.poll}
            gif={gif}
            userCanVote={false}
            parentElementId={containerId}
          />
        </Stack>
      </Stack>
    </Box>
  );
};

export default SharedPostEmbedded;
