import React, { useCallback, useMemo } from 'react';
import { Drawer as MUIDrawer, SxProps, useMediaQuery, useTheme } from '@mui/material';

type DrawerProps = {
  sx?: SxProps;
  anchor?: 'left' | 'right' | 'top' | 'bottom';
  variant?: 'temporary' | 'persistent' | 'permanent';
  children: React.ReactNode;
  open?: boolean;
  onClose?: () => void;
  keepMounted?: boolean;
};

/**
 * The Dialog component in Material UI has a maximum width of 444px at the 'xs' breakpoint.
 * To maintain consistency, we use the same value as the max width for the Drawer component,
 * but only for the 'sm' breakpoint and above.
 * At the 'xs' breakpoint, the Drawer should occupy the full width.
 * @see https://github.com/mui/material-ui/blob/v5.15.17/packages/mui-material/src/Dialog/Dialog.js
 */
const MAX_WIDTH = 444;

function DrawerComp(props: DrawerProps) {
  const { sx, anchor = 'right', variant = 'temporary', open = false, onClose, keepMounted = false } = props;
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down('sm'));
  const anchorPosition = isMobile ? 'bottom' : anchor;
  const handleClose = useCallback(() => {
    if (onClose) onClose();
  }, [onClose]);

  const sxProps = useMemo(
    () => ({
      backgroundImage: 'none',
      boxShadow: '-10px 4px 42px 0px rgba(0, 0, 0, 0.25)',
      width: {
        sm: '30%'
      },
      maxWidth: {
        sm: MAX_WIDTH
      },
      [theme.breakpoints.down('sm')]: {
        width: '100% !important',
        maxWidth: '100% !important'
      }
    }),
    [theme.breakpoints]
  );

  return (
    <MUIDrawer
      {...props}
      anchor={anchorPosition}
      onClose={handleClose}
      open={open}
      PaperProps={{ sx: { ...sxProps, ...sx } }}
      variant={variant}
      keepMounted={keepMounted}
    >
      {props.children}
    </MUIDrawer>
  );
}

const Drawer = React.memo(DrawerComp);

export { Drawer };
