import { Helmet } from 'react-helmet-async';
import { useMutation, useQuery } from 'react-query';
import { useNavigate } from 'react-router';

import { IconEdit, IconX } from '@material-hu/icons/tabler';
import CircularProgress from '@material-hu/mui/CircularProgress';
import IconButton from '@material-hu/mui/IconButton';
import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';

import useHuSnackbar from '@material-hu/components/design-system/Snackbar';

import { useAuth } from 'src/contexts/JWTContext';
import useGeneralError from 'src/hooks/useGeneralError';
import useHuGoTheme from 'src/hooks/useHuGoTheme';
import useRequiredParams from 'src/hooks/useRequiredParams';
import { getDraftDetail, reviewDraftPost } from 'src/services/posts';
import { ApprovalStatus } from 'src/types/groups';
import { formatTitle } from 'src/utils/helmetUtils';
import { useLokaliseTranslation } from 'src/utils/i18n';

import DraftStepperLayout from '../components/DraftStepper/DraftStepperLayout';
import PostDraftCard from '../components/PostDraftCard';
import ScheduledPostAlert from '../components/ScheduledPostAlert';
import { invalidateDrafts, postDraftKeys } from '../queries';
import { draftsForReviewRoutes } from '../routes';
import { checkIsFinalAuthor } from '../utils';

const DraftDetail = () => {
  const navigate = useNavigate();
  const { user: loggedUser } = useAuth();
  const { id: draftId } = useRequiredParams(['id']);
  const { t } = useLokaliseTranslation(['drafts', 'communication']);
  const showGeneralError = useGeneralError();
  const { enqueueSnackbar } = useHuSnackbar();

  const { data: draftDetail, isLoading: isLoadingDetail } = useQuery(
    postDraftKeys.draftDetail(draftId),
    () => getDraftDetail(Number(draftId)),
    { enabled: true, select: res => res.data },
  );

  const { mutate, isLoading } = useMutation(
    () => reviewDraftPost(Number(draftId), ApprovalStatus.APPROVED),
    {
      onSuccess: () => {
        enqueueSnackbar({
          title: t('drafts:detail.approve_draft_success_title'),
          description: t(
            'communication:drafts_for_review.success_approve_draft_description',
          ),
          variant: 'success',
        });
        invalidateDrafts();
        navigate(draftsForReviewRoutes.drafts());
      },
      onError: error => {
        showGeneralError(
          error,
          t('communication:drafts_for_review.error_approve_draft'),
        );
      },
    },
  );

  const isFinalAuthor =
    loggedUser &&
    draftDetail?.draftPermission &&
    checkIsFinalAuthor(loggedUser.id, [draftDetail.draftPermission]);

  // Check if edit should be disabled due to poll restrictions
  const canEditDraft =
    isFinalAuthor &&
    (!draftDetail?.post?.poll || draftDetail.post.poll.totalAnswerCount === 0);

  return (
    <>
      <Helmet>
        <title>{formatTitle(t('drafts:main.post'))}</title>
      </Helmet>
      <Stack
        sx={{
          overflowX: 'hidden',
          height: '100%',
          bgcolor: theme => theme.palette.new.background.layout.default,
        }}
      >
        <>
          <Stack
            sx={{
              overflowX: 'hidden',
              height: '100%',
              bgcolor: theme => theme.palette.new.background.layout.default,
            }}
          >
            <Stack
              sx={{
                alignItems: 'center',
                flexDirection: 'row',
                justifyContent: 'space-between',
                bgcolor: theme => theme.palette.new.background.layout.tertiary,
                gap: 2,
                py: 2,
                px: 3,
              }}
            >
              <Typography
                variant="globalL"
                fontWeight="fontWeightSemiBold"
              >
                {t('drafts:main.post')}
              </Typography>
              <IconButton
                onClick={() => navigate(draftsForReviewRoutes.drafts())}
              >
                <IconX />
              </IconButton>
            </Stack>
            {isLoadingDetail && (
              <Stack sx={{ alignItems: 'center', p: 4 }}>
                <CircularProgress />
              </Stack>
            )}
            {!isLoadingDetail && (
              <DraftStepperLayout
                withFooter={!!isFinalAuthor}
                primaryButtonProps={
                  isFinalAuthor
                    ? {
                        onClick: () => mutate(),
                        text: t('APPROVE'),
                        isLoading: isLoading,
                      }
                    : undefined
                }
                secondaryButtonProps={
                  canEditDraft && draftId
                    ? {
                        text: t('EDIT'),
                        onClick: () =>
                          navigate(draftsForReviewRoutes.edit(draftId)),
                        icon: <IconEdit size={16} />,
                      }
                    : undefined
                }
                tertiaryButtonProps={
                  isFinalAuthor
                    ? {
                        text: t('GO_BACK'),
                        onClick: () => navigate(draftsForReviewRoutes.drafts()),
                        disabled: isLoading,
                      }
                    : undefined
                }
              >
                {draftDetail && (
                  <ScheduledPostAlert draftDetail={draftDetail} />
                )}
                {draftDetail && <PostDraftCard draftRequest={draftDetail} />}
              </DraftStepperLayout>
            )}
          </Stack>
        </>
      </Stack>
    </>
  );
};

const DraftDetailWithHugoTheme = () => {
  const HuGoThemeProvider = useHuGoTheme();
  return (
    <HuGoThemeProvider>
      <DraftDetail />
    </HuGoThemeProvider>
  );
};

export default DraftDetailWithHugoTheme;
