import React, { useCallback } from "react";
import { Button, List, Popover } from "antd";
import { Paragraph } from "@/components/Typography/Paragraph";
import { TypographyPresets } from "@/components/Typography/Preset";
import "@/app/css/ModuleEditor.scss"; // use styles from the original source file

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

interface ModuleEditorProps {
  children: React.ReactNode;
  data?: PopoverMenuItem[];
  title?: string;
  visible?: boolean; // controlled visibility (v4: visible, v5: open)
  onChangeVisible?: (value: boolean) => void; // setter for visibility
}

const ModuleEditor = ({
  children,
  data = [],
  title,
  visible,
  onChangeVisible,
}: ModuleEditorProps) => {
  const handleClickItem = useCallback(
    (item: PopoverMenuItem) => () => {
      // mirror original: close first, then execute the action
      onChangeVisible?.(false);
      item.onClick?.();
    },
    [onChangeVisible]
  );

  const renderItems = () =>
    data.map((item) => (
      <List.Item
        className={item.itemClassName}
        key={item.key}
        onClick={handleClickItem(item)}
      >
        <Paragraph
          ellipsis
          preset={item.labelPreset || "semibold14"}
          className={item.className}
        >
          {item.label}
        </Paragraph>
      </List.Item>
    ));

  // Support both antd v4 and v5 props (harmless on either)
  const popProps: any = {
    placement: "bottomRight",                  // original placement
    overlayClassName: "module-editor-overlay", // original overlay class
    trigger: ["click"],                        // original trigger
    arrow: false,                              // v5 way to hide arrow
    arrowContent: null,                        // v4 compatibility (noop on v5)
    content: (
      <List className="popover-menu-actions module-editor__acitons">
        {title && (
          <List.Item className="title">
            <Paragraph className="opacity--06" preset="semibold14">
              {title}
            </Paragraph>
          </List.Item>
        )}
        {renderItems()}
      </List>
    ),
    // controlled visibility
    visible,                 // v4
    onVisibleChange: onChangeVisible,
    open: visible,           // v5
    onOpenChange: onChangeVisible,
  };

  return (
    <Popover {...popProps}>
      <Button
        className="p--0 d--flex align__items--center height--24 min-h-auto"
        type="link"
        onClick={(e) => {
          // keep scope-local toggle; match original stopPropagation behavior
          e.stopPropagation();
          onChangeVisible?.(true);
        }}
      >
        {children}
      </Button>
    </Popover>
  );
};

export default ModuleEditor;
