import { FC, useEffect } from 'react';
import { Helmet } from 'react-helmet-async';
import { Navigate } from 'react-router-dom';

import { StreamVideo } from '@stream-io/video-react-sdk';

import Box from '@material-hu/mui/Box';
import CircularProgress from '@material-hu/mui/CircularProgress';
import Container from '@material-hu/mui/Container';

import { logEvent } from 'src/config/logging';
import { EVENTS_SOCKETS } from 'src/constants/sockets';
import { useAuth } from 'src/contexts/JWTContext';
import { useSocket } from 'src/contexts/SocketContext';
import useFeed from 'src/hooks/queryHooks/feed';
import useHuGoTheme from 'src/hooks/useHuGoTheme';
import useRequiredParams from 'src/hooks/useRequiredParams';
import {
  addFeedDetailDataReaction,
  removeFeedDetailDataReaction,
} from 'src/pages/dashboard/feed/queries';
import { feedRoutes } from 'src/pages/dashboard/feed/routes';
import useGetStreamVideoClient from 'src/pages/dashboard/liveStream/hooks/useGetStreamVideoClient';
import { EventName } from 'src/types/amplitude';
import { PostReactionSocket } from 'src/types/posts';
import { UserTypeStream } from 'src/types/stream';
import { formatTitle } from 'src/utils/helmetUtils';
import { useLokaliseTranslation as useTranslation } from 'src/utils/i18n';

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

const PostDetail: FC = () => {
  const { id } = useRequiredParams(['id'], -1);
  const { t } = useTranslation();
  const socket = useSocket();
  const { user } = useAuth();
  const { feedDetail } = useFeed();
  const client = useGetStreamVideoClient(UserTypeStream.VIEWER);

  const { data, isLoading } = feedDetail(id);
  const HugoThemeProvider = useHuGoTheme();

  useEffect(() => {
    logEvent(EventName.POST_DETAILS_VIEW, { postId: id });
  }, [id]);

  useEffect(() => {
    const addPostReaction = (reaction: PostReactionSocket) => {
      const { emoji, unified, userId, postId } = reaction;

      addFeedDetailDataReaction(postId, emoji, unified, userId === user?.id);
    };

    const removePostReaction = (reaction: PostReactionSocket) => {
      const { emoji, userId, postId } = reaction;

      removeFeedDetailDataReaction(postId, emoji, userId === user?.id);
    };

    socket.listenEvent(EVENTS_SOCKETS.NEW_POST_REACTION, addPostReaction);

    socket.listenEvent(EVENTS_SOCKETS.REMOVE_POST_REACTION, removePostReaction);

    return () => {
      socket.closeEvent(EVENTS_SOCKETS.NEW_POST_REACTION, addPostReaction);

      socket.closeEvent(
        EVENTS_SOCKETS.REMOVE_POST_REACTION,
        removePostReaction,
      );
    };
  }, [socket, user?.id]);

  const post = data?.data;

  if (!isLoading && !post) {
    return (
      <Navigate
        to={feedRoutes.feed()}
        replace
      />
    );
  }

  const handleAddReaction = (
    postId: number,
    emoji: string,
    unified: string,
  ) => {
    addFeedDetailDataReaction(postId, emoji, unified);
  };

  const handleRemoveReaction = (postId: number, emoji: string) => {
    removeFeedDetailDataReaction(postId, emoji);
  };

  return (
    <HugoThemeProvider>
      <StreamVideo client={client}>
        <Helmet>
          <title>{formatTitle(t('post:feed'))}</title>
        </Helmet>

        <Box
          sx={theme => ({
            backgroundColor: theme.palette.new.background.layout.default,
            minHeight: '100%',
            pt: 2,
            pb: 8,
          })}
        >
          <Container maxWidth="sm">
            {isLoading && (
              <Box sx={{ textAlign: 'center' }}>
                <CircularProgress />
              </Box>
            )}
            {!isLoading && post && (
              <Box sx={{ mt: 3 }}>
                <PostCard
                  isDetail
                  onAddReaction={handleAddReaction}
                  onRemoveReaction={handleRemoveReaction}
                  post={post}
                />
              </Box>
            )}
          </Container>
        </Box>
      </StreamVideo>
    </HugoThemeProvider>
  );
};

export default PostDetail;
