import { Close } from '@mui/icons-material'
import {
  Box,
  Dialog,
  DialogProps,
  DialogTitle,
  Grow,
  IconButton,
  styled,
} from '@mui/material'
import { TransitionProps } from '@mui/material/transitions'
import { forwardRef, ReactNode, useState } from 'react'
import { SCROLLBAR_DARK } from '../../theme/muiTheme'
import ErrorBoundary from '../ErrorBoundary/ErrorBoundary'

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

const StyledDialogContent = styled(Box)(() => ({
  width: '100%',
  padding: '1rem',
  maxHeight: 'calc(100vh - 64px)',
  overflow: 'auto',
  ...SCROLLBAR_DARK,
}))

export const Transition = forwardRef(function Transition(
  props: TransitionProps & {
    children: React.ReactElement
  },
  ref: React.Ref<unknown>,
) {
  return <Grow timeout={1000} ref={ref} {...props} />
})

interface DrawerButtonProps {
  anchor: (props: { open: () => void }) => ReactNode
  content: (props: { close: () => void }) => ReactNode
  title: string
  dialogProps?: Omit<DialogProps, 'open'>
  onDialogClose?: () => void
}

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

  const onClose = () => {
    onDialogClose && onDialogClose()
    setOpen(false)
  }

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

  return (
    <>
      {anchor({
        open: onOpen,
      })}
      <CustomDialog
        open={open}
        content={content}
        dialogProps={dialogProps}
        onClose={onClose}
        title={title}
      />
    </>
  )
}

interface CustomDialogProps {
  content: (props: { close: () => void }) => ReactNode
  title?: string
  onClose: () => void
  open: boolean
  dialogProps?: Omit<DialogProps, 'open'>
}

export const CustomDialog = ({
  onClose,
  dialogProps,
  title,
  content,
  open,
}: CustomDialogProps) => {
  const props = {
    PaperProps: {
      ...dialogProps?.PaperProps,
      elevation: 2,
      sx: { borderRadius: '10px' },
    },
    fullWidth: true,
    onClose: onClose,
    open: open,
    transitionDuration: 140,
    TransitionComponent: Transition,
    sx: {
      ...dialogProps?.sx,
      '& .MuiBackdrop-root': { backgroundColor: 'rgba(0, 0, 0, 0.4)' },
    },
    ...dialogProps,
  }

  return (
    <Dialog {...props}>
      {title && (
        <StyledDialogHeader>
          <DialogTitle>{title}</DialogTitle>
          <IconButton onClick={onClose} sx={{ color: 'black' }}>
            <Close />
          </IconButton>
        </StyledDialogHeader>
      )}
      <StyledDialogContent>
        <ErrorBoundary>{content({ close: onClose })}</ErrorBoundary>
      </StyledDialogContent>
    </Dialog>
  )
}
