import { type FC, useMemo } from 'react';
import { useMutation, useQuery } from 'react-query';
import { useNavigate } from 'react-router-dom';

import { IconSpeakerphone } from '@material-hu/icons/tabler';
import Stack from '@material-hu/mui/Stack';

import HuAccordion from '@material-hu/components/design-system/Accordion';
import Button from '@material-hu/components/design-system/Buttons/Button';

import usePermissions from 'src/hooks/usePermissions';
import { feedKeys } from 'src/pages/dashboard/feed/queries';
import { feedRoutes } from 'src/pages/dashboard/feed/routes';
import { groupsRoutes } from 'src/pages/dashboard/groups/routes';
import {
  getKeyUpdatesPreview,
  getUnreadKeyUpdatesCount,
  markKeyUpdateAsRead,
} from 'src/services/posts';
import { FileTypes } from 'src/types/attachments';
import { type Post } from 'src/types/posts';
import { useLokaliseTranslation as useTranslation } from 'src/utils/i18n';
import { UserPermissions } from 'src/utils/permissions';

import PostCard from 'src/components/post/PostCard';

type KeyUpdatesAlertProps = {
  sourceId?: number | null;
};

const KeyUpdatesAlert: FC<KeyUpdatesAlertProps> = ({ sourceId }) => {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const { hasAll: canViewKeyUpdates } = usePermissions([
    UserPermissions.VIEW_KEY_UPDATES,
  ]);

  const { data: unreadCount, isLoading } = useQuery(
    feedKeys.keyUpdates.unread(),
    () => getUnreadKeyUpdatesCount(),
    {
      select: res => res.data.keyUpdateNotifications ?? 0,
      enabled: canViewKeyUpdates,
    },
  );
  const { data: keyUpdatesPreviewPosts, isLoading: isLoadingPreviewPosts } =
    useQuery(feedKeys.keyUpdates.preview(), () => getKeyUpdatesPreview(), {
      select: res => res.data.items ?? [],
      enabled: canViewKeyUpdates,
    });

  const { mutate: markAsRead } = useMutation((postId: number) =>
    markKeyUpdateAsRead(postId),
  );

  const hasUnread = unreadCount ? unreadCount > 0 : false;
  const hasPreviewPosts = !!keyUpdatesPreviewPosts?.length;

  const description = useMemo(() => {
    if (hasUnread) {
      return t('post:key_updates_description');
    }
    if (hasPreviewPosts) {
      return t('post:key_updates_description_preview');
    }
    return undefined;
  }, [hasUnread, hasPreviewPosts, t]);

  const handleClick = () => {
    navigate(feedRoutes.keyUpdates(sourceId));
  };

  const handlePostClick = async (postId: number, groupId?: number) => {
    await markAsRead(postId);
    if (groupId) {
      navigate(groupsRoutes.post.detail(groupId, postId));
    } else {
      navigate(feedRoutes.post.detail(postId));
    }
  };

  if (isLoading || isLoadingPreviewPosts || !canViewKeyUpdates) {
    return null;
  }

  const filterAttachments = (post: Post) => {
    if (post.bodyHtml?.length) {
      return [];
    }

    const mediaAttachments = post.attachments.filter(
      attachment =>
        FileTypes.VIDEO === attachment.type ||
        FileTypes.IMAGE === attachment.type ||
        FileTypes.GIF === attachment.type,
    );

    const gifAttachments = post.attachments.filter(
      attachment => attachment.type === FileTypes.GIF,
    );

    const otherAttachments = post.attachments.filter(
      attachment =>
        attachment.type !== FileTypes.VIDEO &&
        attachment.type !== FileTypes.IMAGE &&
        attachment.type !== FileTypes.GIF,
    );

    if (mediaAttachments.length) {
      return mediaAttachments;
    }

    if (gifAttachments.length) {
      return gifAttachments;
    }

    return otherAttachments;
  };

  return (
    <HuAccordion
      elevation={0}
      sx={{
        border: _theme =>
          `1px solid ${_theme.palette.new.border.neutral.default}`,
        borderRadius: _theme => _theme.shape.borderRadiusL,
      }}
      title={t('post:key_updates')}
      avatar={{ Icon: IconSpeakerphone, color: 'highlight' }}
      defaultExpanded={hasUnread || hasPreviewPosts}
      square
      description={description}
      customDetail={
        <Stack>
          {hasPreviewPosts && (
            <Stack
              direction="row"
              sx={{ gap: 1, my: 1, mb: 2 }}
            >
              {keyUpdatesPreviewPosts?.map(post => (
                <PostCard
                  key={post.id}
                  post={{
                    ...post,
                    attachments: filterAttachments(post),
                    poll: null,
                  }}
                  elementId={`post-card-key-update-preview-${post.id}`}
                  abbreviateDate
                  hideKeyUpdateHeader
                  hideAction
                  hideComments
                  hideReactions
                  hideTranslation
                  hidePinIcon
                  mediaMaxHeight={250}
                  showSeeMoreToggle={
                    !!post.bodyHtml?.length &&
                    (!!post.attachments.length || !!post.poll?.id)
                  }
                  onShowMore={() => handlePostClick(post.id, post.group?.id)}
                  onClick={() => handlePostClick(post.id, post.group?.id)}
                />
              ))}
            </Stack>
          )}
          <Button
            variant={hasUnread ? 'contained' : 'secondary'}
            onClick={handleClick}
          >
            {hasUnread
              ? t('post:unread_posts', { count: unreadCount })
              : t('post:see_all')}
          </Button>
        </Stack>
      }
    />
  );
};

export default KeyUpdatesAlert;
