import { useState } from "react";
import DragIndicatorOutlined from "@mui/icons-material/DragIndicatorOutlined";
import { SearchBox } from "@/shared/ui/SearchBox.jsx";
import { adminListClasses } from "@/shared/ui/AdminListLayout.jsx";

export function MenuTreePanel({
  abilities,
  menus,
  onQueryChange,
  onReorder,
  onSelect,
  query,
  selectedMenuId,
  total
}) {
  const [draggingMenu, setDraggingMenu] = useState(null);
  const [dragOverId, setDragOverId] = useState(null);

  return (
    <section className="menu-tree-panel">
      <div className="menu-tree-panel__header">
        <div className="menu-panel-title">
          <h2>菜单树</h2>
          <span>共 {total} 项</span>
        </div>
        <SearchBox placeholder="搜索菜单、路由、权限码" value={query} onChange={onQueryChange} />
      </div>
      <div className="menu-tree-list" role="tree">
        {menus.length ? (
          menus.map((menu) => {
            const isSelected = menu.id === selectedMenuId;
            const rowProps = getDragRowProps({
              canSort: abilities.canSortMenu,
              dragOverId,
              draggingMenu,
              menu,
              onDragEnd: () => {
                setDraggingMenu(null);
                setDragOverId(null);
              },
              onDragOverRow: setDragOverId,
              onDragStart: setDraggingMenu,
              onReorder
            });
            const { className = "", ...restRowProps } = rowProps;

            return (
              <button
                {...restRowProps}
                aria-selected={isSelected}
                className={[
                  "menu-tree-item",
                  isSelected ? "menu-tree-item--active" : "",
                  className
                ].filter(Boolean).join(" ")}
                key={menu.id || menu.code}
                role="treeitem"
                style={{ paddingLeft: `${16 + menu.depth * 18}px` }}
                type="button"
                onClick={() => onSelect(menu)}
              >
                <span className="menu-tree-item__drag">
                  {abilities.canSortMenu ? <DragIndicatorOutlined fontSize="small" /> : null}
                </span>
                <span className="menu-tree-item__content">
                  <span className="menu-tree-item__name">{menu.label}</span>
                  <span className="menu-tree-item__meta">{menu.path || menu.code}</span>
                </span>
                <span className={["menu-tree-status", menu.visible !== false ? "is-visible" : "is-hidden"].join(" ")}>
                  {menu.visible !== false ? "显示" : "隐藏"}
                </span>
              </button>
            );
          })
        ) : (
          <div className="empty-state empty-state--compact">
            <div className="empty-state__title">当前无数据</div>
          </div>
        )}
      </div>
    </section>
  );
}

function getDragRowProps({ canSort, dragOverId, draggingMenu, menu, onDragEnd, onDragOverRow, onDragStart, onReorder }) {
  if (!canSort) {
    return {};
  }

  const canDrop = draggingMenu && draggingMenu.id !== menu.id && (draggingMenu.parentId || null) === (menu.parentId || null);
  const isDropTarget = canDrop && dragOverId === menu.id;

  return {
    className: [adminListClasses.dragRow, isDropTarget ? adminListClasses.dragRowActive : ""].filter(Boolean).join(" "),
    draggable: true,
    onDragEnd,
    onDragLeave: () => {
      if (dragOverId === menu.id) {
        onDragOverRow(null);
      }
    },
    onDragOver: (event) => {
      if (canDrop) {
        event.preventDefault();
        event.dataTransfer.dropEffect = "move";
        onDragOverRow(menu.id);
      }
    },
    onDragStart: (event) => {
      event.dataTransfer.effectAllowed = "move";
      event.dataTransfer.setData("text/plain", String(menu.id));
      onDragStart(menu);
    },
    onDrop: (event) => {
      event.preventDefault();
      if (canDrop) {
        onReorder(draggingMenu, menu);
      }
      onDragOverRow(null);
      onDragEnd();
    }
  };
}
