import type { ReactNode } from "react"
import { Popover, type PopoverProps } from "@mui/material"
import { alpha, styled } from "@mui/material/styles"

// ----------------------------------------------------------------------

type ArrowPlacement =
  | "top-left"
  | "top-center"
  | "top-right"
  | "bottom-left"
  | "bottom-center"
  | "bottom-right"
  | "left-top"
  | "left-center"
  | "left-bottom"
  | "right-top"
  | "right-center"
  | "right-bottom"

const ArrowStyle = styled("span")(({ theme }) => ({
  [theme.breakpoints.up("sm")]: {
    top: -7,
    zIndex: 1,
    width: 12,
    right: 20,
    height: 12,
    content: "''",
    position: "absolute",
    borderRadius: "0 0 4px 0",
    transform: "rotate(-135deg)",
    background: theme.palette.background.paper,
    borderRight: `solid 1px ${alpha(theme.palette.grey[500], 0.12)}`,
    borderBottom: `solid 1px ${alpha(theme.palette.grey[500], 0.12)}`,
  },
}))

// ----------------------------------------------------------------------

interface MenuPopoverProps extends Omit<PopoverProps, "children"> {
  children: ReactNode
  arrow?: ArrowPlacement
  disabledArrow?: boolean
}

export function MenuPopover({ children, arrow = "top-right", disabledArrow, sx, ...other }: MenuPopoverProps) {
  return (
    <Popover
      anchorOrigin={{ vertical: "bottom", horizontal: "right" }}
      transformOrigin={{ vertical: "top", horizontal: "right" }}
      PaperProps={{
        sx: {
          p: 1,
          width: 200,
          overflow: "inherit",
          ...sx,
        },
      }}
      {...other}
    >
      {!disabledArrow && <ArrowStyle className="arrow" />}
      {children}
    </Popover>
  )
}
