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

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

import useFeed from 'src/hooks/queryHooks/feed';
import useHuGoTheme from 'src/hooks/useHuGoTheme';
import useRequiredParams from 'src/hooks/useRequiredParams';
import { formatTitle } from 'src/utils/helmetUtils';
import { useLokaliseTranslation as useTranslation } from 'src/utils/i18n';

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

import { feedRoutes } from './routes';

const FeedPostSharePage: FC = () => {
  const { id } = useRequiredParams(['id'], -1);
  const { t } = useTranslation(['post']);
  const navigate = useNavigate();
  const HugoThemeProvider = useHuGoTheme();
  const { feedDetail } = useFeed();

  const { data, isLoading, isError } = feedDetail(id);
  const post = data?.data;

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

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

export default FeedPostSharePage;
