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

import CardHeader from '@material-hu/mui/CardHeader';
import Link from '@material-hu/mui/Link';
import Stack from '@material-hu/mui/Stack';
import Tooltip from '@material-hu/mui/Tooltip';
import Typography from '@material-hu/mui/Typography';

import HuCardContainer from '@material-hu/components/design-system/CardContainer';
import Pills from '@material-hu/components/design-system/Pills';

import { MAX_NAME_LENGTH } from 'src/constants/posts';
import { usePostAttachments } from 'src/hooks/usePostAttachments';
import { GenericPostMenu } from 'src/pages/dashboard/feed/components/GenericPostMenu';
import { invalidateFeedPendingApprovalPostList } from 'src/pages/dashboard/feed/queries';
import { invalidateGroupPendingApprovalPostList } from 'src/pages/dashboard/groups/queries';
import { profileRoutes } from 'src/pages/dashboard/profile/routes';
import { EventName } from 'src/types/amplitude';
import { type FeedPendingPost } from 'src/types/feed';
import { ApprovalStatus, type GroupPendingPost } from 'src/types/groups';
import { PostRequestActionType } from 'src/types/posts';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { truncateText } from 'src/utils/text';
import { getFullName } from 'src/utils/userUtils';

import { PostCardFeatures } from 'src/components/post/PostCardFeatures';
import TimeDistance from 'src/components/time/TimeDistance';
import ProfilePicture from 'src/components/user/ProfilePicture';

import PostBody from '../post/PostBody';

import { getPostWithPendingContent } from './getPostWithPendingContent';
import PendingApprovalPostDelete from './PendingApprovalPostDelete';

const MAX_CHARACTERS_LIMIT = 250;
const MAX_NEW_LINES_LIMIT = 4;

type PendingApprovalPostListCardProps = {
  pendingPost: GroupPendingPost | FeedPendingPost;
  closeScheduledPostList: () => void;
};

export const PendingApprovalPostListCard: FC<
  PendingApprovalPostListCardProps
> = props => {
  const { pendingPost } = props;
  const { t } = useLokaliseTranslation();
  const isFeedPost = (pendingPost as FeedPendingPost).post !== undefined;

  const {
    post: basePost,
    amplitudeEventName,
    groupId,
    invalidatePendingApprovalPostList,
  } = isFeedPost
    ? {
        post: (pendingPost as FeedPendingPost).post,
        amplitudeEventName: EventName.FEED_POST_DELETED,
        groupId: undefined,
        invalidatePendingApprovalPostList:
          invalidateFeedPendingApprovalPostList,
      }
    : {
        post: (pendingPost as GroupPendingPost).groupPost,
        amplitudeEventName: EventName.GROUPS_POST_DELETED,
        groupId: (pendingPost as GroupPendingPost).groupPost.groupId,
        invalidatePendingApprovalPostList: () =>
          invalidateGroupPendingApprovalPostList(
            (pendingPost as GroupPendingPost).groupPost.groupId,
          ),
      };
  const isEditionRequest =
    pendingPost.actionType === PostRequestActionType.EDITION;
  const post = getPostWithPendingContent(
    basePost,
    pendingPost.postContent,
    pendingPost.updatedAt,
  );

  const { mediaList, fileList, audioList, gif } = usePostAttachments(
    post.attachments,
  );

  const handleDelete = () => {
    invalidatePendingApprovalPostList();
  };

  const menuOptions = [
    {
      id: 'delete-post',
      enabled: true,
      option: (
        <PendingApprovalPostDelete
          requestId={pendingPost.id}
          postId={post.id}
          onDelete={handleDelete}
          groupId={groupId}
          amplitudeEventName={amplitudeEventName}
        />
      ),
    },
  ];

  // TODO: should use UnifiedPostCard
  return (
    <HuCardContainer
      key={pendingPost.id}
      sx={{
        p: 1,
        mb: 2,
        border: '1px solid',
        borderColor: theme => theme.palette.new.border.neutral.default,
      }}
      fullWidth
    >
      <CardHeader
        sx={{
          '& .MuiCardHeader-avatar': { mr: 1 },
          p: 0,
          pb: 2,
        }}
        avatar={
          <ProfilePicture
            id={post.user.id}
            user={post.user}
            openInNewTab
            withLink
          />
        }
        subheader={
          <Stack sx={{ flexDirection: 'row', alignItems: 'center' }}>
            <TimeDistance
              typographySx={{ variant: 'globalXS', fontWeight: 'regular' }}
              date={new Date(post.publicationDatetime)}
              showIcon={false}
            />
          </Stack>
        }
        title={
          <Stack
            sx={{
              flexDirection: 'row',
              alignItems: 'center',
              WebkitLineClamp: 2,
              WebkitBoxOrient: 'vertical',
              overflow: 'hidden',
            }}
          >
            <Tooltip
              title={
                getFullName(post.user).length > MAX_NAME_LENGTH
                  ? getFullName(post.user)
                  : ''
              }
            >
              <Link
                component={RouterLink}
                to={profileRoutes.profile(post.user.id)}
                target="_blank"
                rel="noopener noreferrer"
                variant="globalS"
                sx={{
                  display: 'inline',
                  verticalAlign: 'middle',
                  color: theme => theme.palette.new.text.neutral.default,
                  textDecoration: 'none',
                  fontWeight: 'semiBold',
                  transition: 'color 0.2s',
                  '&:hover': {
                    color: theme => theme.palette.new.text.neutral.brand,
                    textDecoration: 'underline',
                  },
                }}
              >
                {truncateText(getFullName(post.user), MAX_NAME_LENGTH)}
              </Link>
            </Tooltip>
          </Stack>
        }
        action={
          <Stack
            sx={{
              flexDirection: 'row',
              alignItems: 'center',
              gap: 1,
            }}
          >
            {isEditionRequest && (
              <Pills
                label={t('post:edited')}
                type="info"
                size="small"
                hasIcon={false}
              />
            )}
            {menuOptions.length > 0 && (
              <GenericPostMenu
                id={post.id}
                menuOptions={menuOptions}
              />
            )}
          </Stack>
        }
      />

      <PostBody
        bodyHtml={post.bodyHtml}
        body={post.body}
        bodyAttributes={post.bodyAttributes}
        maxCharacters={MAX_CHARACTERS_LIMIT}
        maxNewLines={MAX_NEW_LINES_LIMIT}
      />

      <PostCardFeatures
        id={post.id}
        poll={post.poll}
        gif={gif}
        mediaList={mediaList}
        fileList={fileList}
        audioList={audioList}
        linkPreviews={post.linkPreviews}
        grantVideoDownload
        approvalStatus={ApprovalStatus.PENDING}
      />
    </HuCardContainer>
  );
};
