import { Grow, Popover, PopoverProps } from '@mui/material'
import { TransitionProps } from '@mui/material/transitions'
import { ReactNode, forwardRef, useState } from 'react'

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

interface PopoverButtonProps {
  anchor: (props: { open: (e: any) => void }) => ReactNode
  content: (props: { close: () => void }) => ReactNode
  popoverProps?: Omit<PopoverProps, 'open'>
  onDialogClose?: () => void
}

export default function PopoverButton({
  content,
  popoverProps,
  onDialogClose,
  anchor,
}: PopoverButtonProps) {
  const [popperAnchor, setPopperAnchor] = useState(null)

  const onClose = () => {
    onDialogClose && onDialogClose()
    setPopperAnchor(null)
  }

  const onOpen = (e) => {
    setPopperAnchor(e.currentTarget)
  }

  return (
    <>
      {anchor({
        open: onOpen,
      })}
      <CustomPopover
        open={Boolean(popperAnchor)}
        content={content}
        popoverProps={popoverProps}
        onClose={onClose}
        popperAnchor={popperAnchor}
      />
    </>
  )
}

interface CustomDialogProps {
  content: (props: { close: () => void }) => ReactNode
  onClose: () => void
  open: boolean
  popoverProps?: Omit<PopoverProps, 'open'>
  popperAnchor: any
}

export const CustomPopover = ({
  onClose,
  popoverProps,
  content,
  open,
  popperAnchor,
}: CustomDialogProps) => {
  return (
    <>
      <Popover
        onClose={onClose}
        open={open}
        transitionDuration={140}
        TransitionComponent={Transition}
        PaperProps={{
          ...popoverProps?.PaperProps,
          elevation: 2,
          sx: {
            borderRadius: '10px',
            border: '1px solid #1212121A',
            boxShadow: '0px 4px 16px #0000000F',
          },
        }}
        anchorEl={popperAnchor}
        anchorOrigin={{
          vertical: 'bottom',
          horizontal: 'left',
        }}
        sx={{
          ...popoverProps?.sx,
        }}
        {...popoverProps}
      >
        {content({ close: onClose })}
      </Popover>
    </>
  )
}
