import React, { FC } from 'react';
import { AnimatePresence } from 'framer-motion';
import { ModalProps } from 'types';
import Portal from '../Portal';
import { Box, Button, Fade, Slide } from '../wrappers';
import { useComponentLogic } from './hooks';
import { closeButtonVariants, fadeVariants, overlayVariants } from './variants';

export const Modal: FC<ModalProps> = props => {
	const { children, className, close, id, open, ...rest } = props;
	const { ref } = useComponentLogic(props);
	return (
		<AnimatePresence>
			<Portal id={`modal-${id}`}>
				{open && (
					<>
						<Fade position="fixed" isVisible={open} variants={fadeVariants}>
							<Slide direction="vertical" distance={75} isVisible={open}>
								<Box
									className={className}
									ref={ref}
									minH="20vh"
									minW="20vw"
									{...rest}>
									<Button
										animate="animate"
										className={`${className}__close-button`}
										height="2rem"
										onClick={close}
										position="absolute"
										radius="1rem"
										variants={closeButtonVariants}
										width="2rem">
										X
									</Button>
									{children}
								</Box>
							</Slide>
						</Fade>
						<Box
							animate="animate"
							bottom={0}
							className={`${className}__overlay`}
							exit="exit"
							left={0}
							position="fixed"
							right={0}
							top={0}
							variants={overlayVariants}
						/>
					</>
				)}
			</Portal>
		</AnimatePresence>
	);
};

Modal.defaultProps = {
	className: '',
	id: 'missing-id',
	shouldCloseOnClickOutside: false,
};

export default Modal;
