import { Close } from '@mui/icons-material'
import {
  Box,
  ButtonProps,
  DialogTitle,
  Drawer,
  DrawerProps,
  IconButton,
  styled,
} from '@mui/material'
import { ReactNode, useState } from 'react'
import { SCROLLBAR_DARK } from '../../theme/muiTheme'
import ErrorBoundary from '../ErrorBoundary/ErrorBoundary'

const StyledDrawerHeader = styled(Box)(({ theme }) => ({
  height: '64px',
  backgroundColor: '#f7f7f7',
  display: 'flex',
  justifyContent: 'space-between',
  alignItems: 'end',
  padding: '0.6rem 1rem',
  paddingBottom: '10px',
}))

const StyledDrawerContent = styled(Box)(({ theme }) => ({
  padding: '1rem',
  height: 'calc(100vh - 64px)',
  overflowY: 'auto',
  paddingBottom: '4rem',
  ...SCROLLBAR_DARK,
}))

export interface DrawerButtonProps {
  anchor: (props: { open: () => void }) => ReactNode
  content: (props: { close: () => void }) => ReactNode
  title: string | ReactNode
  btnTxt?: string | ReactNode
  btnProps?: ButtonProps
}

export default function DrawerButton({
  content,
  title,
  anchor,
}: DrawerButtonProps) {
  const [open, setOpen] = useState(false)

  const onOpen = () => {
    setOpen(true)
  }

  const onClose = () => {
    setOpen(false)
  }
  return (
    <>
      {anchor({ open: onOpen })}
      <CustomDrawer
        content={content}
        onClose={onClose}
        open={open}
        title={title}
      />
    </>
  )
}

interface CustomDrawerProps {
  content: (props: { close: () => void }) => ReactNode
  title: string | ReactNode
  drawerProps?: Omit<DrawerProps, 'open'>
  onClose: () => void
  open: boolean
}

export const CustomDrawer = ({
  onClose,
  drawerProps,
  title,
  content,
  open,
}: CustomDrawerProps) => {
  return (
    <Drawer
      anchor="right"
      elevation={2}
      onClose={onClose}
      open={open}
      PaperProps={{
        ...drawerProps?.PaperProps,
        elevation: 2,
      }}
      sx={{
        ...drawerProps?.sx,
        zIndex: 500,
        '& .MuiDrawer-paper': {
          boxSizing: 'border-box',
          width: 600,
        },
        '& .MuiBackdrop-root': {
          backgroundColor: 'rgba(0, 0, 0, 0.4)',
        },
      }}
      transitionDuration={140}
      {...drawerProps}
    >
      <StyledDrawerHeader>
        <DialogTitle>{title}</DialogTitle>
        <IconButton onClick={onClose} sx={{ color: 'black' }}>
          <Close />
        </IconButton>
      </StyledDrawerHeader>
      <StyledDrawerContent>
        <ErrorBoundary>{content({ close: onClose })}</ErrorBoundary>
      </StyledDrawerContent>
    </Drawer>
  )
}
