import React from "react";
import { Popover as PopoverComponent } from "@mui/material";
import "./Popover.styles.scss";
import CloseIcon from "@mui/icons-material/Close";
import { Button } from "../Button";

export function Popover({
  children,
  title,
  onClose,
  primaryButtonLabel,
  secondaryButtonLabel,
  onPrimaryButtonClick,
  onSecondaryButtonClick,
  primaryButtonProps,
  secondaryButtonProps,
  PaperProps: paperPropsFromUser,
  ...props
}) {
  return (
    <PopoverComponent
      {...props}
      onClose={onClose}
      PaperProps={{
        ...paperPropsFromUser,
        className: ["popover-container", paperPropsFromUser?.className]
          .filter(Boolean)
          .join(" "),
      }}
    >
      <div className="popover-content">
        <div className="popover-header">
          <span className="popover-header-title">{title}</span>
          {onClose && (
            <CloseIcon
              fontSize="small"
              onClick={onClose}
              sx={{ color: "#60697D", cursor: "pointer" }}
              tabIndex={0}
              onKeyDown={(e) => {
                if (e.key === "Enter" || e.key === " ") {
                  e.preventDefault();
                  onClose();
                }
              }}
              className="popover-close-icon"
            />
          )}
        </div>
        <div className="popover-body">{children}</div>
        <div className="popover-footer">
          <div className="popover-footer-content">
            {primaryButtonLabel || secondaryButtonLabel ? (
              <div className="divider-line" />
            ) : null}
            <div className="popover-footer-buttons">
              {secondaryButtonLabel && (
                <Button
                  variant="tertiary"
                  onClick={onSecondaryButtonClick}
                  {...secondaryButtonProps}
                >
                  {secondaryButtonLabel}
                </Button>
              )}
              {primaryButtonLabel && (
                <Button
                  variant="primary"
                  onClick={onPrimaryButtonClick}
                  {...primaryButtonProps}
                >
                  {primaryButtonLabel}
                </Button>
              )}
            </div>
          </div>
        </div>
      </div>
    </PopoverComponent>
  );
}
