import { type FC } from 'react';
import { Helmet } from 'react-helmet-async';
import { useQuery } from 'react-query';
import { Navigate, useNavigate } from 'react-router-dom';

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

import useGeneralError from 'src/hooks/useGeneralError';
import useHuGoTheme from 'src/hooks/useHuGoTheme';
import useRequiredParams from 'src/hooks/useRequiredParams';
import { getGroupPostDetails } from 'src/services/groups';
import { formatTitle } from 'src/utils/helmetUtils';
import { useLokaliseTranslation as useTranslation } from 'src/utils/i18n';

import { SharePageContent } from 'src/components/post/SharePost';

import { groupsKeys } from './queries';
import { groupsRoutes } from './routes';

const GroupPostSharePage: FC = () => {
  const { id: groupId, postId } = useRequiredParams(['id', 'postId'], -1);
  const { t } = useTranslation(['post', 'group']);
  const navigate = useNavigate();
  const HugoThemeProvider = useHuGoTheme();
  const showGeneralError = useGeneralError();

  const {
    data: post,
    isLoading,
    isError,
  } = useQuery(
    groupsKeys.postDetail(groupId, postId),
    () => getGroupPostDetails(groupId, postId, { skipNotFoundRedirect: true }),
    {
      select: response => response.data,
      onError: err => {
        showGeneralError(err, t('post:error_loading_post_detail'));
      },
      staleTime: 0,
    },
  );

  if (!isLoading && isError) {
    return (
      <Navigate
        to={groupsRoutes.detail(groupId)}
        replace
      />
    );
  }

  return (
    <HugoThemeProvider>
      <Helmet>
        <title>{formatTitle(t('group:groups'))}</title>
      </Helmet>
      {isLoading && (
        <Box sx={{ display: 'flex', justifyContent: 'center', pt: 8 }}>
          <CircularProgress />
        </Box>
      )}
      {!isLoading && post && (
        <SharePageContent
          originalPost={post}
          onSuccess={() => navigate(groupsRoutes.detail(groupId))}
          onCancel={() => navigate(-1)}
        />
      )}
    </HugoThemeProvider>
  );
};

export default GroupPostSharePage;
