import { Helmet } from 'react-helmet-async';
import { useForm, FormProvider } from 'react-hook-form';
import { useQuery } from 'react-query';
import { useMutation } from 'react-query';
import { useSearchParams, useNavigate, Navigate } from 'react-router-dom';

import Stack from '@material-hu/mui/Stack';

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 {
  getInstanceForRestorePassword,
  updatePasswordWithCode,
} from 'src/services/authService';
import { formatTitle } from 'src/utils/helmetUtils';
import { useLokaliseTranslation } from 'src/utils/i18n';

import HuFormStrongPassword from 'src/components/FormInputs/HuFormStrongPassword';

import RegistrationLayout from './components/RegistrationLayout';
import { registrationKeys } from './queries';

type RestorePasswordFormValues = {
  code: string;
  passwordInput: string;
  repeatPasswordInput: string;
};

const RestorePassword = () => {
  const navigate = useNavigate();
  const { t } = useLokaliseTranslation('authentication');
  const { enqueueSnackbar } = useHuSnackbar();
  const showGeneralError = useGeneralError();
  const [searchParams] = useSearchParams();
  const HugoThemeProvider = useHuGoTheme();

  const updatePasswordMutation = useMutation(updatePasswordWithCode, {
    onSuccess: () => {
      navigate('/');
      enqueueSnackbar({
        title: t('SUCCESS_RESET_PASSWORD'),
        variant: 'success',
      });
    },
    onError: (err: any) => showGeneralError(err, t('ERROR_RESET_PASSWORD')),
  });

  const code = searchParams.get('code');

  const { data: instance } = useQuery(
    registrationKeys.instance(),
    () => getInstanceForRestorePassword(code!),
    { enabled: !!code },
  );

  const form = useForm<RestorePasswordFormValues>({
    defaultValues: {
      code: code!,
      passwordInput: '',
      repeatPasswordInput: '',
    },
  });

  const {
    handleSubmit,
    formState: { isSubmitting },
  } = form;

  const submit = (values: RestorePasswordFormValues) => {
    updatePasswordMutation.mutate(values);
  };

  if (!code) {
    return <Navigate to="/" />;
  }

  return (
    <>
      <Helmet>
        <title>{formatTitle(t('UPDATE.TITLE'))}</title>
      </Helmet>
      <HugoThemeProvider>
        <RegistrationLayout title={t('UPDATE.TITLE')}>
          <FormProvider {...form}>
            <form
              noValidate
              onSubmit={handleSubmit(submit)}
            >
              <Stack sx={{ alignItems: 'center', gap: 4 }}>
                <HuFormStrongPassword
                  passwordType={instance?.data?.passwordType!}
                />
                <Button
                  type="submit"
                  variant="primary"
                  size="large"
                  disabled={isSubmitting}
                  sx={{ width: '100%' }}
                >
                  {t('UPDATE.SUBMIT')}
                </Button>
              </Stack>
            </form>
          </FormProvider>
        </RegistrationLayout>
      </HugoThemeProvider>
    </>
  );
};

export default RestorePassword;
