import { useFormContext } from 'react-hook-form';
import { useNavigate } from 'react-router';

import { useModal } from '@material-hu/hooks/useModal';
import CloseIcon from '@material-hu/icons/material/Close';
import IconButton from '@material-hu/mui/IconButton';
import Stack from '@material-hu/mui/Stack';

import HuDialog from '@material-hu/components/design-system/Dialog';
import HuTitle from '@material-hu/components/design-system/Title';

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

import { eventsRoutes } from '../routes';

export const FocusNavbar = ({
  children,
  eventId,
}: {
  children: React.ReactNode;
  eventId?: number;
}) => {
  const { t } = useLokaliseTranslation('events');
  const navigate = useNavigate();
  const {
    formState: { isDirty },
  } = useFormContext();
  const isCreating = !eventId;

  const handleClose = () => {
    if (isCreating) {
      return navigate(eventsRoutes.events());
    }
    return navigate(eventsRoutes.event(eventId));
  };

  const { modal, showModal, closeModal } = useModal(
    () => (
      <HuDialog
        onClose={closeModal}
        title={t(
          'CREATE_EVENT_FORM.' +
            (isCreating ? 'PREVENT_MODAL_TITLE' : 'PREVENT_EDIT_MODAL_TITLE'),
        )}
        textBody={t('CHANGES_WILL_BE_LOST')}
        primaryButtonProps={{
          children: t('general:yes'),
          onClick: handleClose,
        }}
        secondaryButtonProps={{
          children: t('general:cancel'),
          onClick: closeModal,
        }}
      />
    ),
    { maxWidth: 'sm' },
  );

  const handleCloseClick = () => {
    if (!isCreating && !isDirty) {
      handleClose();
      return;
    }
    showModal();
  };

  return (
    <Stack
      sx={{
        width: '100%',
        backgroundColor: theme => theme.palette.new.background.layout.default,
      }}
    >
      <Stack
        sx={{
          flexDirection: 'row',
          justifyContent: 'space-between',
          alignItems: 'center',
          backgroundColor: theme =>
            theme.palette.new.background.layout.tertiary,
          py: 1,
        }}
      >
        <HuTitle
          title={t(isCreating ? 'CREATE_EVENT' : 'EDIT_EVENT')}
          variant="L"
          sx={{ px: 3, py: 2 }}
        />
        <IconButton onClick={handleCloseClick}>
          <CloseIcon />
        </IconButton>
      </Stack>
      {children}
      {modal}
    </Stack>
  );
};
