import React, { FC } from 'react';
// TODO @grsmto: might be worth migrating to react-pose once https://github.com/reach/reach-ui/issues/126 is fixed
import { Transition } from 'react-spring/renderprops.cjs';
import { ModalBase } from '../ModalBase';
import { Grid } from '../Grid';
import * as sc from './styles';
import { SvgArrow } from '../../assets/images/icons';

interface Props extends React.ComponentProps<typeof ModalBase> {
  onClose?: () => void;
  maxWidth?: number | string;
  scroll?: 'body' | 'inner';
}

export const ModalDrawer: FC<Props> = ({
  children,
  isOpen: isOpenProps,
  onClose,
  isCloseable,
  isCentered,
  maxWidth,
  scroll,
  ...otherProps
}) => {
  const handleCloseRequest = () => {
    if (!isCloseable) return;
    if (onClose) onClose();
  };

  return (
    <ModalBase isOpen={isOpenProps} onClose={onClose} isCentered={isCentered}>
      <Transition
        native
        items={isOpenProps}
        from={{ transform: 'translate3d(-110%, 0, 0)' }}
        enter={{ transform: 'translate3d(0, 0, 0)' }}
        leave={{ transform: 'translate3d(-110%, 0, 0)' }}
      >
        {(isOpen) =>
          isOpen &&
          ((styles) => (
            <sc.Container style={styles} aria-label="modal drawer content">
              <sc.Dialog
                scroll={scroll}
                maxWidth={maxWidth}
                p={4}
                borderRadius={0}
                boxShadow={4}
                {...otherProps}
              >
                <Grid gridAutoFlow="column">
                  {isCloseable && (
                    <sc.CloseButton
                      Asset={SvgArrow}
                      onClick={handleCloseRequest}
                      variant="primary"
                    />
                  )}
                  <sc.Inner>{children}</sc.Inner>
                </Grid>
              </sc.Dialog>
            </sc.Container>
          ))
        }
      </Transition>
    </ModalBase>
  );
};

ModalDrawer.defaultProps = {
  ...ModalBase.defaultProps,
  maxWidth: 1,
};
