import React from "react";
import { CollapsibleMenuSection } from "./CollapsibleMenuSection";
import { MenuItem } from "./MenuItem";
import { useDispatch } from "react-redux";
import { OPEN_MODAL } from "../../../lib/redux/slices/appSlice";

export const RoleMenuRenderer = React.memo(
  ({ menuConfig, open, openSub, onToggleSub, onClose }) => {
    const dispatch = useDispatch();

    const handleModalItem = (item) => {
      if (item.isModal && item.modalContent) {
        const ModalContent = item.modalContent;
        dispatch(
          OPEN_MODAL({
            title: item.modalTitle || "اطلاعات",
            content: React.isValidElement(ModalContent) ? (
              ModalContent
            ) : (
              <ModalContent />
            ),
          })
        );
      }
    };

    return (
      <>
        {menuConfig.collapsibleSections?.map((section) => (
          <CollapsibleMenuSection
            key={section.key}
            icon={section.icon}
            text={section.text}
            tooltip={section.tooltip}
            open={open}
            isExpanded={openSub[section.key] || false}
            onToggle={() => onToggleSub(section.key)}
            items={section.items}
            onClose={onClose}
          />
        ))}

        {menuConfig.regularItems?.map((item, index) => {
          if (item.isModal) {
            return (
              <MenuItem
                key={index}
                {...item}
                open={open}
                onClick={() => handleModalItem(item)}
                onClose={onClose}
              />
            );
          }
          return (
            <MenuItem key={index} {...item} open={open} onClose={onClose} />
          );
        })}
      </>
    );
  }
);

RoleMenuRenderer.displayName = "RoleMenuRenderer";
