import { Modal } from '@material-ui/core';
import { makeStyles } from '@material-ui/core/styles';
import React, { Dispatch, SetStateAction } from 'react';

type Dispatcher<S> = Dispatch<SetStateAction<S>>;

interface ICustomModalProps {
  isOpen: boolean;
  setIsOpen: Dispatcher<boolean>;
  children: React.ReactNode;
  customStyle: {
    backgroundColor?: string;
    margin?: string;
    padding?: string;
    width?: string;
    border?: string;
    borderRadius?: string;
  };
}

const useStyles = makeStyles((theme) => ({
  modal: (customStyle: ICustomModalProps['customStyle']) => ({
    backgroundColor: 'transparent',
    margin: '7% auto',
    padding: 'none',
    border: 'none',
    width: customStyle.width || '85%',
    [theme.breakpoints.down(700)]: {
      margin: '3% auto',
      width: '95%',
    },
  }),
  modalContent: (customStyle: ICustomModalProps['customStyle']) => ({
    ...{
      backgroundColor: customStyle.backgroundColor || 'theme.palette.background.paper',
      border: customStyle.border || 'none',
      padding: customStyle.padding || 'none',
      borderRadius: customStyle.borderRadius || 'none',
      boxShadow: theme.shadows[5],
      '&:focus': {
        outline: 'none',
      },
    },
  }),
}));

export const CustomModal: React.FC<ICustomModalProps> = ({
  isOpen,
  setIsOpen,
  customStyle = {},
  children,
}: ICustomModalProps) => {
  const classes = useStyles(customStyle);

  const handleClose = (): void => {
    setIsOpen(false);
  };

  const body = <div className={classes.modalContent}>{children}</div>;

  return (
    <div>
      <Modal
        className={classes.modal}
        open={isOpen}
        onClose={handleClose}
        aria-labelledby="custom-modal"
        aria-describedby="custom-modal"
      >
        {body}
      </Modal>
    </div>
  );
};

export default CustomModal;