import { useState } from 'react';

import Dialog from '@material-hu/components/design-system/Dialog';
import { useDialogLayer } from '@material-hu/components/layers/Dialogs';

import { useLokaliseTranslation } from 'src/utils/i18n';

const CONFIRM_DIALOG_ID = 'certificate-create-confirm';

type ConfirmDialogContentProps = {
  /** Runs the activation request; resolves to whether it succeeded. */
  onConfirm: () => Promise<boolean>;
  onClose: () => void;
};

const ConfirmDialogContent = ({
  onConfirm,
  onClose,
}: ConfirmDialogContentProps) => {
  const { t } = useLokaliseTranslation('learning');
  const [isLoading, setIsLoading] = useState(false);

  const handleConfirm = async () => {
    setIsLoading(true);
    const didSucceed = await onConfirm();
    if (didSucceed) {
      onClose();
      return;
    }
    setIsLoading(false);
  };

  return (
    <Dialog
      onClose={onClose}
      title={t('settings.certificates.create_flow.modal.create')}
      textBody={t('settings.certificates.create_flow.modal.create_description')}
      primaryButtonProps={{
        children: t('settings.certificates.create'),
        onClick: handleConfirm,
        loading: isLoading,
      }}
      secondaryButtonProps={{
        children: t('general:cancel'),
        onClick: onClose,
        disabled: isLoading,
      }}
    />
  );
};

type UseCertificateConfirmDialogProps = {
  onConfirm: () => Promise<boolean>;
};

const useCertificateConfirmDialog = ({
  onConfirm,
}: UseCertificateConfirmDialogProps) => {
  const { openDialog, closeDialog } = useDialogLayer();

  const handleClose = () => closeDialog(CONFIRM_DIALOG_ID);

  const openConfirmDialog = () => {
    openDialog(
      {
        content: (
          <ConfirmDialogContent
            onConfirm={onConfirm}
            onClose={handleClose}
          />
        ),
      },
      CONFIRM_DIALOG_ID,
    );
  };

  return { openConfirmDialog };
};

export default useCertificateConfirmDialog;
