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';
import { ModalBase } from '../ModalBase';
import { Header } from './Header';
import { Body } from './Body';
import { Footer } from './Footer';
import * as sc from './styles';
import { ModalStatus } from './types';
import { SvgClose } from '../../assets/images/icons';

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

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

    if (onClose) {
      onClose();
    }
  };

  return (
    <ModalBase isOpen={isOpenProps} onClose={onClose} isCentered={isCentered}>
      <Transition
        native
        items={isOpenProps}
        from={{ opacity: 0 }}
        enter={{ opacity: 1 }}
        leave={{ opacity: 0 }}
      >
        {isOpen =>
          isOpen &&
          (styles => (
            <sc.Container style={styles}>
              <sc.Dialog
                scroll={scroll}
                status={status}
                maxWidth={maxWidth}
                boxShadow={3}
                p={0}
                {...otherProps}
              >
                {!!status && <sc.StatusBar status={status} />}
                {isCloseable && (
                  <sc.CloseButton
                    Asset={SvgClose}
                    onClick={handleCloseRequest}
                    height={44}
                    width={44}
                    color="gray.2"
                    scale={0.62}
                  />
                )}
                {children}
              </sc.Dialog>
            </sc.Container>
          ))
        }
      </Transition>
    </ModalBase>
  );
};

ModalComponent.defaultProps = {
  ...ModalBase.defaultProps,
  maxWidth: 'm',
  scroll: 'body',
};

export const Modal = Object.assign(ModalComponent, {
  defaultProps: ModalComponent.defaultProps,
  Header,
  Body,
  Footer,
});
