import { useEffect } from 'react';
import { Helmet } from 'react-helmet-async';
import { FormProvider } from 'react-hook-form';
import { useNavigate } from 'react-router';
import { useSearchParams } from 'react-router-dom';

import { useModal } from '@material-hu/hooks/useModal';
import { IconX } from '@material-hu/icons/tabler';
import IconButton from '@material-hu/mui/IconButton';
import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';

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

import useHuGoTheme from 'src/hooks/useHuGoTheme';
import usePosting from 'src/hooks/usePosting';
import { createFeedPostDraft, createGroupsPostDraft } from 'src/services/posts';
import { PostData } from 'src/types/posts';
import { formatTitle } from 'src/utils/helmetUtils';
import { useLokaliseTranslation } from 'src/utils/i18n';

import DraftStepper from '../components/DraftStepper';
import { useCheckDraftPermission } from '../hooks/useCheckDraftPermission';
import { draftsForReviewRoutes } from '../routes';

const NewDraft = () => {
  const { t } = useLokaliseTranslation(['communication', 'drafts']);
  const navigate = useNavigate();
  const HuGoThemeProvider = useHuGoTheme();
  const [searchParams, setSearchParams] = useSearchParams();
  const { enqueueSnackbar } = useHuSnackbar();
  useCheckDraftPermission({ checkDrafter: true });

  const permissionId = searchParams.get('permissionId');
  const groupId = searchParams.get('groupId');

  const createDraftPostForGroup =
    (permId: number, id: number) => (data: PostData) =>
      createGroupsPostDraft(permId, id, data);

  const createDraftPostForFeed = (permId: number) => (data: PostData) =>
    createFeedPostDraft(permId, data);

  useEffect(() => {
    if (groupId !== null) {
      searchParams.delete('groupId');
      setSearchParams(searchParams);
    }
  }, []);

  const { form, handleSubmit, submit, ...rest } = usePosting({
    request: groupId
      ? createDraftPostForGroup(Number(permissionId), Number(groupId))
      : createDraftPostForFeed(Number(permissionId)),
    onSuccess: () => {
      enqueueSnackbar({
        title: t('drafts:steps.post.draft_sent'),
        description: t(
          'communication:drafts_for_review.success_create_draft_description',
        ),
        variant: 'success',
      });
      navigate(draftsForReviewRoutes.drafts());
    },
    onError: () => {
      enqueueSnackbar({
        title: t('communication:drafts_for_review.error_create_draft'),
        description: t(
          'communication:drafts_for_review.error_create_draft_description',
        ),
        variant: 'error',
      });
    },
    isDraft: true,
  });

  const {
    modal: confirmationModal,
    showModal: showConfirmationModal,
    closeModal: closeDeleteModal,
  } = useModal(() => (
    <HuDialog
      title={t('drafts:steps.post.confirm_title')}
      textBody={t('communication:drafts_for_review.send_for_approval_body')}
      primaryButtonProps={{
        children: t('communication:drafts_for_review.yes_send'),
        onClick: () => handleSubmit(submit)(),
        loading: rest.isSubmitting,
      }}
      secondaryButtonProps={{
        children: t('general:cancel'),
        onClick: closeDeleteModal,
      }}
      onClose={closeDeleteModal}
    />
  ));

  return (
    <>
      <Helmet>
        <title>{formatTitle(t('drafts:main.create_draft'))}</title>
      </Helmet>
      <HuGoThemeProvider>
        {confirmationModal}
        <FormProvider {...form}>
          <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.create_draft')}
              </Typography>
              <IconButton
                onClick={() => navigate(draftsForReviewRoutes.drafts())}
              >
                <IconX />
              </IconButton>
            </Stack>
            <DraftStepper
              onSubmit={showConfirmationModal}
              usePostingProps={rest}
            />
          </Stack>
        </FormProvider>
      </HuGoThemeProvider>
    </>
  );
};

export default NewDraft;
