import { FC, useState } from 'react';

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

import Button from '@material-hu/components/design-system/Buttons/Button';

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

import AcceptCancelDialog from 'src/components/AcceptCancelDialog';

export type ExitFormButtonProps = {
  onExit?: () => void;
  onCancel?: () => void;
  withConfirmation?: boolean;
  title?: string;
  description?: string;
};

export const ExitFormButton: FC<ExitFormButtonProps> = props => {
  const {
    onExit = () => null,
    onCancel = () => null,
    withConfirmation = false,
    title,
    description,
  } = props;

  const [openDialogExit, setOpenDialogExit] = useState<boolean>(false);

  const { t } = useLokaliseTranslation('forms');

  const closeDialog = () => setOpenDialogExit(false);
  const openDialog = () => setOpenDialogExit(true);

  const handleExit = () => {
    withConfirmation ? openDialog() : onExit();
  };

  const handleAcceptExit = () => {
    onExit();
    closeDialog();
  };

  const handleCancelExit = () => {
    onCancel();
    closeDialog();
  };

  return (
    <>
      <Button
        component="a"
        sx={{
          mb: 2,
          mx: 'auto',
        }}
        size="small"
        onClick={handleExit}
      >
        {t('EXIT')}
      </Button>
      {openDialogExit && (
        <AcceptCancelDialog
          open={openDialogExit}
          title={title || t('LOSE_DATA_TITLE')}
          showCancel
          onCancel={handleCancelExit}
          onAccept={handleAcceptExit}
        >
          <Typography color="textPrimary">
            {description || t('LOSE_DATA_INFO')}
          </Typography>
        </AcceptCancelDialog>
      )}
    </>
  );
};

export default ExitFormButton;
