import { FC } from 'react';
import { FormProvider, useForm } from 'react-hook-form';
import { useMutation } from 'react-query';

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

import HuDialog from '@material-hu/components/design-system/Dialog';
import HuFormInputPassword from '@material-hu/components/design-system/Inputs/Password/form';

import useRules from 'src/hooks/useRules';
import { documentLogin } from 'src/services/documents';
import { useLokaliseTranslation } from 'src/utils/i18n';

export type DocumentPasswordProps = {
  onSuccess: () => void;
  onCancel: () => void;
};

const DocumentPassword: FC<DocumentPasswordProps> = props => {
  const { onSuccess, onCancel } = props;
  const { t } = useLokaliseTranslation(['documents', 'authentication']);

  const passwordRules = useRules({
    requiredWithMessage: true,
  });

  const { mutate, isLoading: isLoadingDocumentLogin } = useMutation(
    (password: string) => documentLogin(password),
    {
      onSuccess,
      onError: () => {
        setError('passwordInput', {
          type: 'custom',
          message: t('INCORRECT_PASSWORD'),
        });
      },
    },
  );

  const form = useForm({
    defaultValues: {
      passwordInput: '',
    },
  });

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

  const passwordInput = watch('passwordInput');

  const submit = values => mutate(values.passwordInput);

  return (
    <HuDialog
      title={t('AUTHENTICATION_REQUIRED')}
      onClose={onCancel}
      body={
        <Stack>
          <Typography sx={{ mb: 2 }}>{t('ENTER_PASSWORD')}</Typography>
          <FormProvider {...form}>
            <form
              noValidate
              onSubmit={handleSubmit(submit)}
            >
              <HuFormInputPassword
                name="passwordInput"
                rules={passwordRules}
                inputProps={{
                  placeholder: t('AUTHENTICATION:PASSWORD'),
                }}
              />
            </form>
          </FormProvider>
        </Stack>
      }
      primaryButtonProps={{
        children: t('CONTINUE'),
        onClick: handleSubmit(submit),
        disabled: isSubmitting || isLoadingDocumentLogin || !passwordInput,
        loading: isSubmitting || isLoadingDocumentLogin,
      }}
      secondaryButtonProps={{
        children: t('CANCEL'),
        onClick: onCancel,
        disabled: isSubmitting || isLoadingDocumentLogin,
        loading: isSubmitting || isLoadingDocumentLogin,
      }}
    />
  );
};

export default DocumentPassword;
