import { Button, List, Popover } from "antd";
import { Paragraph, TypographyPresets } from "components/Typography";
import * as React from "react";
import { useCallback } from "react";
import "./PopoverMenu.scss";

export type PopoverMenuItem = {
  key: string;
  label: string;
  onClick?: () => void;
  className?: string;
  itemClassName?: string;
  labelPreset?: TypographyPresets;
};

interface PopoverMenuProps {
  children: React.ReactNode;
  data?: PopoverMenuItem[];
  title?: string;
  visible?: boolean;
  onChangeVisible?: (value: boolean) => void;
}

const PopoverMenu = ({
  children,
  data = [],
  title,
  visible,
  onChangeVisible,
}: PopoverMenuProps) => {
  const handleClickItem = useCallback(
    (item) => () => {
      onChangeVisible?.(false);
      item.onClick?.();
    },
    [data]
  );

  const renderItems = () => {
    return data.map((item) => (
      <List.Item
        className={item.itemClassName}
        key={item.key}
        onClick={handleClickItem(item)}
      >
        <Paragraph
          ellipsis={true}
          preset={item.labelPreset || "semibold14"}
          className={item.className}
        >
          {item.label}
        </Paragraph>
      </List.Item>
    ));
  };
  return (
    <Popover
      visible={visible}
      placement="top"
      overlayClassName="popover-menu-overlay"
      arrowContent={null}
      content={
        <List className="popover-menu-actions ">
          {title && (
            <List.Item className="title">
              <Paragraph className="opacity--06" preset="semibold14">
                {title}
              </Paragraph>
            </List.Item>
          )}
          {renderItems()}
        </List>
      }
      trigger={["click"]}
      onVisibleChange={onChangeVisible}
    >
      <Button
        className="p--0 d--flex align__items--center height--24 min-h-auto"
        type="link"
        onClick={() => onChangeVisible?.(true)}
      >
        {children}
      </Button>
    </Popover>
  );
};

export default PopoverMenu;
