import { Helmet } from 'react-helmet-async';
import { FormProvider, useForm } from 'react-hook-form';
import { useTranslation } from 'react-i18next';
import { useMutation } from 'react-query';
import { useNavigate } from 'react-router';

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

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

import useGeneralError from 'src/hooks/useGeneralError';
import useHuGoTheme from 'src/hooks/useHuGoTheme';
import {
  CreateDraftPermissionBody,
  createDraftPermission,
} from 'src/services/posts';
import { User } from 'src/types/user';
import { formatTitle } from 'src/utils/helmetUtils';
import { validateObjectNullableRule } from 'src/utils/validation';

import UsersAutocomplete from 'src/components/UsersAutocomplete';

import { draftsForReviewRoutes } from './routes';

const FOOTER_HEIGHT = 84;
const CONTAINER_MAX = 800;

const CreateDraftPermission = () => {
  const { t } = useTranslation(['drafts', 'general']);
  const navigate = useNavigate();
  const { enqueueSnackbar } = useHuSnackbar();
  const showGeneralError = useGeneralError();
  const HuGoThemeProvider = useHuGoTheme();

  const form = useForm<{
    draftCreator: User | null;
    finalAuthor: User | null;
  }>({
    defaultValues: {
      draftCreator: null,
      finalAuthor: null,
    },
    mode: 'onChange',
    reValidateMode: 'onChange',
  });

  const { formState, watch } = form;

  const {
    mutate: createCreateDraftPermission,
    isLoading: isCreatingPermission,
  } = useMutation(
    (body: CreateDraftPermissionBody) => createDraftPermission(body),
    {
      onSuccess: () => {
        enqueueSnackbar({
          title: t('create_success'),
          variant: 'success',
        });
        navigate(draftsForReviewRoutes.base());
      },
      onError: err => showGeneralError(err),
    },
  );

  const handleCreate = () => {
    const { draftCreator, finalAuthor } = form.getValues();

    if (draftCreator === null || finalAuthor === null) {
      return;
    }

    createCreateDraftPermission({
      userFromId: draftCreator.id,
      userToId: finalAuthor.id,
    });
  };

  const commonAutocompleteProps = {
    textFieldProps: {
      label: '',
      margin: 'normal' as const,
      sx: {
        mt: 0.5,
        bgcolor: (theme: Theme) =>
          theme.palette.hugoBackground?.neutralBgTerciary,
      },
      placeholder: t('general:search'),
    },
    rules: {
      validate: validateObjectNullableRule([null], t('must_select_user')),
    },
    autocompleteProps: {
      loadingText: `${t('GENERAL:LOADING')}...`,
      noOptionsText: t('GENERAL:NO_RESULTS'),
    },
  };

  return (
    <>
      <Helmet>
        <title>{formatTitle(t('grant_permission'))}</title>
      </Helmet>
      <HuGoThemeProvider>
        <FormProvider {...form}>
          <Stack
            sx={{
              overflowX: 'hidden',
              height: '100%',
              bgcolor: theme => theme.palette.hugoBackground?.neutralBg,
            }}
          >
            <Stack
              sx={{
                alignItems: 'center',
                flexDirection: 'row',
                justifyContent: 'space-between',
                bgcolor: theme =>
                  theme.palette.hugoBackground?.neutralBgTerciary,
                gap: 2,
                py: 2,
                px: 3,
              }}
            >
              <Typography
                variant="globalL"
                fontWeight="fontWeightSemiBold"
              >
                {t('grant_permission')}
              </Typography>
              <IconButton
                onClick={() => navigate(draftsForReviewRoutes.base())}
              >
                <IconX />
              </IconButton>
            </Stack>
            <Stack
              sx={{
                width: '100%',
                alignItems: 'center',
                height: '100%',
                overflowX: 'hidden',
                overflowY: 'scroll',
                p: 4,
              }}
            >
              <Stack
                sx={{
                  maxWidth: `${CONTAINER_MAX}px`,
                  width: '100%',
                }}
              >
                <Typography
                  variant="globalM"
                  fontWeight="fontWeightSemiBold"
                >
                  {t('select_collaborator')}
                </Typography>
                <Typography
                  variant="globalS"
                  fontWeight="fontWeightSemiBold"
                  sx={{ mt: 2 }}
                >
                  {t('choice_draft_creator')}
                </Typography>
                {/* TODO: Migrate user autocomplete with HuGo */}
                <UsersAutocomplete
                  {...commonAutocompleteProps}
                  name="draftCreator"
                  autocompleteProps={{
                    filterOptions: options =>
                      options.filter(u => u.id !== watch('finalAuthor')?.id),
                  }}
                />
                <Typography
                  variant="globalXXS"
                  color="text.secondary"
                >
                  {t('creator_helper_text')}
                </Typography>
                <Typography
                  variant="globalS"
                  fontWeight="fontWeightSemiBold"
                  sx={{ mt: 2 }}
                >
                  {t('final_author')}
                </Typography>
                {/* TODO: Migrate user autocomplete with HuGo */}
                <UsersAutocomplete
                  {...commonAutocompleteProps}
                  name="finalAuthor"
                  autocompleteProps={{
                    filterOptions: options =>
                      options.filter(u => u.id !== watch('draftCreator')?.id),
                  }}
                />
                <Typography
                  variant="globalXXS"
                  color="text.secondary"
                >
                  {t('final_author_helper_text')}
                </Typography>
              </Stack>
            </Stack>
            <Stack
              sx={{
                flexDirection: 'row',
                justifyContent: 'center',
                bgcolor: theme =>
                  theme.palette.hugoBackground?.neutralBgSecondary,
                height: `${FOOTER_HEIGHT}px`,
              }}
            >
              <Stack
                sx={{
                  flexDirection: 'row',
                  justifyContent: 'end',
                  alignItems: 'center',
                  flex: 1,
                  maxWidth: `${CONTAINER_MAX}px`,
                }}
              >
                <Button
                  variant="primary"
                  onClick={handleCreate}
                  disabled={isCreatingPermission || !formState.isValid}
                  size="large"
                >
                  {t('grant_permission')}
                </Button>
              </Stack>
            </Stack>
          </Stack>
        </FormProvider>
      </HuGoThemeProvider>
    </>
  );
};

export default CreateDraftPermission;
