import React from "react";
import {
  fileToolbarMeta,
  fileToolbarOrder,
  nodeToolbarMeta,
  nodeToolbarOrder,
  type FileToolbarKey,
  type NodeToolbarKey,
} from "./mindmapToolbarConfig";

const stopEditorEvent = (e: React.SyntheticEvent) => {
  e.stopPropagation();
};

type ToolbarProps = {
  canBack: boolean;
  canForward: boolean;
  painterMode: boolean;
  onUndo: () => void;
  onRedo: () => void;
  onPainter: () => void;
  onSibling: () => void;
  onChild: () => void;
  onDelete: () => void;
  onImage: () => void;
  onIcon: () => void;
  onLink: () => void;
  onNote: () => void;
  onTag: () => void;
  onSummary: () => void;
  onAssociativeLine: () => void;
  onFormula: () => void;
  onAttachment: () => void;
  onOuterFrame: () => void;
  onAnnotation?: () => void;
  onAi: () => void;
  onImport: (e: React.ChangeEvent<HTMLInputElement>) => void;
  onNew: () => void;
  onOpenDirectory: () => void;
  onSaveAs: () => void;
  onDeleteMindmap: () => void;
  onExportJson: () => void;
  onExportPng: () => void;
  onExportSvg: () => void;
  onExportPdf: () => void;
  onExportMd: () => void;
  onExportTxt: () => void;
  onExportXmind: () => void;
  fileInputRef: React.RefObject<HTMLInputElement | null>;
};

const ToolbarButton = ({
  iconClass,
  label,
  onClick,
  disabled = false,
  active = false,
  className = "",
}: {
  iconClass: string;
  label: string;
  onClick?: () => void;
  disabled?: boolean;
  active?: boolean;
  className?: string;
}) => (
  <button
    type="button"
    contentEditable={false}
    onPointerDown={stopEditorEvent}
    onMouseDown={stopEditorEvent}
    onClick={(e) => {
      stopEditorEvent(e);
      onClick?.();
    }}
    disabled={disabled}
    className={`flex flex-col items-center justify-center gap-1 px-2 py-1 transition-colors hover:bg-gray-50 disabled:cursor-not-allowed disabled:opacity-40 ${
      active ? "bg-blue-50 text-blue-600" : "text-gray-600"
    } ${className}`}
    title={label}
  >
    <div
      className={`flex h-7 w-7 items-center justify-center rounded border shadow-sm transition-colors ${
        active ? "border-blue-200 bg-white" : "border-gray-200 bg-white"
      }`}
    >
      <i className={`iconfont ${iconClass} text-[15px] leading-none`} />
    </div>
    <span className="text-[10px] font-medium leading-tight whitespace-nowrap">
      {label}
    </span>
  </button>
);

export const MindmapToolbar = ({
  canBack,
  canForward,
  painterMode,
  onUndo,
  onRedo,
  onPainter,
  onSibling,
  onChild,
  onDelete,
  onImage,
  onIcon,
  onLink,
  onNote,
  onTag,
  onSummary,
  onAssociativeLine,
  onFormula,
  onAttachment,
  onOuterFrame,
  onAnnotation,
  onAi,
  onImport,
  onNew,
  onOpenDirectory,
  onSaveAs,
  onDeleteMindmap,
  onExportJson,
  onExportPng,
  onExportSvg,
  onExportPdf,
  onExportMd,
  onExportTxt,
  onExportXmind,
  fileInputRef,
}: ToolbarProps) => {
  const [showExport, setShowExport] = React.useState(false);

  const nodeHandlers: Record<NodeToolbarKey, () => void> = {
    back: onUndo,
    forward: onRedo,
    painter: onPainter,
    siblingNode: onSibling,
    childNode: onChild,
    deleteNode: onDelete,
    image: onImage,
    icon: onIcon,
    link: onLink,
    note: onNote,
    tag: onTag,
    summary: onSummary,
    associativeLine: onAssociativeLine,
    formula: onFormula,
    attachment: onAttachment,
    outerFrame: onOuterFrame,
    annotation: onAnnotation ?? (() => window.alert("标注功能开发中")),
    ai: onAi,
  };

  const fileHandlers: Record<FileToolbarKey, () => void> = {
    directory: onOpenDirectory,
    newFile: onNew,
    openFile: () => fileInputRef.current?.click(),
    import: () => fileInputRef.current?.click(),
    saveAs: onSaveAs,
    deleteFile: onDeleteMindmap,
    exportMenu: () => setShowExport((v) => !v),
  };

  const getNodeDisabled = (key: NodeToolbarKey) => {
    if (key === "back") return !canBack;
    if (key === "forward") return !canForward;
    return false;
  };

  return (
    <div
      className="flex w-full items-center justify-between gap-4 overflow-x-auto [scrollbar-width:none] [-ms-overflow-style:none] [&::-webkit-scrollbar]:hidden"
      contentEditable={false}
      onPointerDownCapture={(e) => e.stopPropagation()}
      onMouseDownCapture={(e) => e.stopPropagation()}
    >
      {/* Left Section: Edit & Node Operations */}
      <div className="flex shrink-0 items-center gap-1 rounded-lg border border-gray-100 bg-white px-2 py-1 shadow-sm">
        {nodeToolbarOrder.map((key) => {
          const meta = nodeToolbarMeta[key];
          const onClick = nodeHandlers[key];
          return (
            <ToolbarButton
              key={key}
              iconClass={meta.iconClass}
              label={meta.label}
              onClick={onClick}
              disabled={getNodeDisabled(key)}
              active={key === "painter" ? painterMode : false}
            />
          );
        })}
      </div>

      {/* Right Section: File & Export Actions */}
      <div className="flex shrink-0 items-center gap-1 rounded-lg border border-gray-100 bg-white px-2 py-1 shadow-sm">
        {fileToolbarOrder.map((key) => {
          const meta = fileToolbarMeta[key];
          const onClick = fileHandlers[key];
          return (
            <ToolbarButton
              key={key}
              iconClass={meta.iconClass}
              label={meta.label}
              onClick={onClick}
            />
          );
        })}
        <input
          ref={fileInputRef}
          type="file"
          accept=".json,.smm,.xmind,.mmap,.md,.markdown,application/json,application/vnd.mindjet.mindmanager,application/x-mindmanager"
          className="hidden"
          onChange={onImport}
        />
        {showExport ? (
          <div className="absolute right-2 top-full z-50 mt-2 w-40 overflow-hidden rounded-lg border border-gray-200 bg-white shadow-lg">
            {[
              { label: "JSON", onClick: onExportJson },
              { label: "PNG", onClick: onExportPng },
              { label: "SVG", onClick: onExportSvg },
              { label: "PDF", onClick: onExportPdf },
              { label: "Markdown", onClick: onExportMd },
              { label: "TXT", onClick: onExportTxt },
              { label: "XMind", onClick: onExportXmind },
            ].map((item) => (
              <button
                key={item.label}
                type="button"
                className="flex w-full items-center justify-between px-3 py-2 text-left text-sm text-gray-700 hover:bg-gray-50"
                contentEditable={false}
                onPointerDown={stopEditorEvent}
                onMouseDown={stopEditorEvent}
                onClick={(e) => {
                  stopEditorEvent(e);
                  setShowExport(false);
                  item.onClick();
                }}
              >
                <span>{item.label}</span>
                <i className="iconfont iconexport text-[12px]" />
              </button>
            ))}
          </div>
        ) : null}
      </div>
    </div>
  );
};
