import { useEffect, useState } from 'react';

import { useModal } from '@material-hu/hooks/useModal';

import { useAuth } from 'src/contexts/JWTContext';
import { getDecodedToken } from 'src/utils/api';

import DocumentsPassword from '../components/DocumentsPassword';

const MILLISECONDS_PER_MINUTE = 60000;

export const useAskForPassword = ({
  onSuccess,
  onCancel,
}: {
  onSuccess?: () => void;
  onCancel?: () => void;
}) => {
  const [shouldGivePassword, setShouldGivePassword] = useState(false);

  const { instance } = useAuth();

  const { loginSso } = getDecodedToken();
  const hasDocumentsPassword =
    instance?.passwordInDocumentsTimer && !instance?.forceOTP && !loginSso;

  const saveDocumentAccess = () =>
    hasDocumentsPassword &&
    localStorage.setItem(
      'lastDocumentAccessTimestamp',
      new Date().getTime().toString(),
    );

  const dismissPasswordPrompt = () => setShouldGivePassword(false);

  const askForPassword = (callback: () => void = () => {}) => {
    const lastTimestamp = localStorage.getItem('lastDocumentAccessTimestamp');

    if (
      hasDocumentsPassword &&
      (!lastTimestamp ||
        new Date().getTime() - parseInt(lastTimestamp, 10) >=
          1 * MILLISECONDS_PER_MINUTE)
    ) {
      setShouldGivePassword(true);
    } else {
      saveDocumentAccess();
      callback();
    }
  };

  const { modal, showModal, closeModal } = useModal(
    DocumentsPassword,
    {
      onClose: () => {
        dismissPasswordPrompt();
        closeModal();
      },
    },
    {
      onSuccess: () => {
        dismissPasswordPrompt();
        saveDocumentAccess();
        onSuccess?.();
        closeModal();
      },
      onCancel: () => {
        dismissPasswordPrompt();
        onCancel?.();
        closeModal();
      },
    },
  );

  useEffect(() => {
    if (shouldGivePassword) {
      showModal();
    }
  }, [shouldGivePassword]);

  return {
    modal,
    askForPassword,
    shouldGivePassword,
  };
};

export default useAskForPassword;
