import React, {useState} from 'react';
import {useTranslation} from 'react-i18next';
import {useMutation} from 'react-query';
import {Dialog, InputPassword, Typography} from '@components';
import {checkPassword} from '@modules/documents/services';
import {MIN_PASSWORD_LENGTH} from '@shared/constants';

import {styles} from './styles';

export interface DocumentsPasswordDialogProps {
  showDialog: boolean;
  onCloseDialog: () => void;
  onSuccess?: () => void;
}

function DocumentsPasswordDialog({
  showDialog,
  onSuccess,
  onCloseDialog,
}: DocumentsPasswordDialogProps) {
  const {t} = useTranslation();
  const [password, setPassword] = useState('');
  const [hasError, setHasError] = useState(false);

  const {mutate: onCheckPassword, isLoading} = useMutation(checkPassword, {
    onSuccess: () => {
      onCloseDialog();
      setPassword('');
      // Timeout to wait close modal
      setTimeout(() => {
        onSuccess?.();
      }, 500);
    },
    onError: () => {
      setHasError(true);
    },
  });

  const onPressContinue = () => {
    if (password.length < MIN_PASSWORD_LENGTH) {
      setHasError(true);
      return;
    }
    onCheckPassword({password});
  };

  const onChangePassword = (text: string) => {
    hasError && setHasError(false);
    setPassword(text);
  };

  return (
    <Dialog
      fullScreen
      isVisible={showDialog}
      title={t('documents.authentication_required')}
      onClose={onCloseDialog}
      footer={{
        primaryButton: {
          isLoading,
          text: t('general.continue'),
          disabled: !password,
          onPress: onPressContinue,
        },
      }}
      contentStyle={styles.content}>
      <Typography>{t('documents.enter_password')}</Typography>
      <InputPassword
        useBottomSheetTextInput
        value={password}
        onChangeText={onChangePassword}
        placeholder={t('authentication.password')}
        autoCapitalize="none"
        isError={hasError}
        helper={hasError ? t('documents.incorrect_password') : ''}
      />
    </Dialog>
  );
}

export default DocumentsPasswordDialog;
