import React from "react";
import { ChevronRight } from "lucide-react";
import { sidebarTriggers, type SidebarPanel } from "./mindmapSidebarConfig";

type Props = {
  activeSidebar: SidebarPanel | null;
  onSelect: (value: SidebarPanel | null) => void;
};

export const MindmapSidebarTrigger = ({ activeSidebar, onSelect }: Props) => {
  const [show, setShow] = React.useState(true);

  return (
    <div
      className={`absolute top-1/2 z-30 flex -translate-y-1/2 transition-all duration-300 ${
        activeSidebar ? "right-[300px]" : "right-0"
      }`}
      contentEditable={false}
      onPointerDownCapture={(e) => e.stopPropagation()}
      onMouseDownCapture={(e) => e.stopPropagation()}
    >
      <div
        data-testid="mindmap-sidebar-collapse-handle"
        className="absolute -left-4 top-1/2 flex h-12 w-4 -translate-y-1/2 cursor-pointer items-center justify-center rounded-l-md bg-blue-500 text-white shadow-md transition-all hover:-left-6 hover:w-6"
        onClick={(e) => {
          e.stopPropagation();
          setShow((prev) => {
            const next = !prev;
            if (!next) {
              // 避免在 setShow 的 updater 内触发父组件 setState，导致 React 警告
              queueMicrotask(() => onSelect(null));
            }
            return next;
          });
        }}
      >
        <ChevronRight
          className={`h-3 w-3 transition-transform ${show ? "" : "rotate-180"}`}
        />
      </div>

      {show ? (
        <div
          data-testid="mindmap-sidebar-trigger-panel"
          className="flex flex-col overflow-hidden rounded-l-lg border border-gray-200 bg-white shadow-lg"
        >
          {sidebarTriggers
            .filter((item) => item.visible !== false)
            .map((item) => {
              const target = item.target;
              const isActive = activeSidebar === target;
              return (
                <button
                  key={item.value}
                  type="button"
                  contentEditable={false}
                  onPointerDown={(ev) => ev.stopPropagation()}
                  onMouseDown={(ev) => ev.stopPropagation()}
                  onClick={(ev) => {
                    ev.stopPropagation();
                    onSelect(isActive ? null : target);
                  }}
                  className={`flex h-16 w-16 flex-col items-center justify-center gap-1 border-b border-gray-100 p-2 text-gray-600 transition-colors hover:bg-gray-50 last:border-0 ${
                    isActive ? "bg-blue-50 font-medium text-blue-600" : ""
                  }`}
                >
                  <i
                    className={`iconfont ${item.iconClass} text-[18px] leading-none`}
                  />
                  <span className="whitespace-nowrap text-xs">{item.label}</span>
                </button>
              );
            })}
        </div>
      ) : null}
    </div>
  );
};
