'use client';

/**
 * FloatingToolbar Component
 * 浮动工具栏组件 - 选中文本时显示
 */

import React, { useCallback, useEffect, useRef, useMemo } from 'react';
import { useEditorStore } from '../../stores/useEditorStore';
import { cn } from '@/lib/utils';
import { toggleMark } from 'prosemirror-commands';
import {
  Bold,
  Italic,
  Code,
  Link2,
  Strikethrough,
  Underline,
  Highlighter,
} from 'lucide-react';
import { useTranslation } from '@/hooks/useTranslation';

export interface FloatingToolbarProps {
  className?: string;
}

interface ToolbarButton {
  name: string;
  icon: React.ComponentType<{ className?: string }>;
  title: string;
  markName: string;
}

export function FloatingToolbar({ className }: FloatingToolbarProps) {
  const { t } = useTranslation();
  const toolbarButtons = useMemo<ToolbarButton[]>(
    () => [
      { name: 'bold', icon: Bold, title: t.documentEditor.actions.bold, markName: 'bold' },
      { name: 'italic', icon: Italic, title: t.documentEditor.actions.italic, markName: 'italic' },
      { name: 'underline', icon: Underline, title: t.documentEditor.actions.underline, markName: 'underline' },
      { name: 'strike', icon: Strikethrough, title: t.documentEditor.actions.strike, markName: 'strike' },
      { name: 'code', icon: Code, title: t.documentEditor.actions.code, markName: 'code' },
      { name: 'highlight', icon: Highlighter, title: t.documentEditor.actions.highlight, markName: 'highlight' },
      { name: 'link', icon: Link2, title: t.documentEditor.actions.link, markName: 'link' },
    ],
    [t]
  );
  const {
    view,
    isFloatingToolbarVisible,
    floatingToolbarPosition,
    hideFloatingToolbar,
    openLinkEditor,
  } = useEditorStore();
  const toolbarRef = useRef<HTMLDivElement>(null);

  // 检查标记是否激活
  const isMarkActive = useCallback(
    (markName: string) => {
      if (!view) return false;

      const { state } = view;
      const { from, to, empty } = state.selection;
      const markType = state.schema.marks[markName];

      if (!markType) return false;

      if (empty) {
        return !!markType.isInSet(state.storedMarks || state.selection.$from.marks());
      }

      return state.doc.rangeHasMark(from, to, markType);
    },
    [view]
  );

  // 切换标记
  const toggleMarkAction = useCallback(
    (markName: string) => {
      if (!view) return;

      const { state, dispatch } = view;
      const markType = state.schema.marks[markName];

      if (!markType) return;

      // 链接特殊处理
      if (markName === 'link') {
        const { from, to } = state.selection;
        const coords = view.coordsAtPos(from);
        const text = state.doc.textBetween(from, to);

        // 检查是否已有链接
        let existingHref = '';
        state.doc.nodesBetween(from, to, (node) => {
          const linkMark = markType.isInSet(node.marks);
          if (linkMark) {
            existingHref = linkMark.attrs.href;
          }
        });

        openLinkEditor(
          { top: coords.bottom + 8, left: coords.left },
          { href: existingHref, text, from, to }
        );
        hideFloatingToolbar();
        return;
      }

      toggleMark(markType)(state, dispatch);
      view.focus();
    },
    [view, openLinkEditor, hideFloatingToolbar]
  );

  // 监听选区变化
  useEffect(() => {
    if (!view) return;

    const updateToolbar = () => {
      const { state } = view;
      const { selection } = state;
      const { from, to, empty } = selection;

      // 如果选区为空，隐藏工具栏
      if (empty || from === to) {
        hideFloatingToolbar();
        return;
      }

      // 计算工具栏位置
      const start = view.coordsAtPos(from);
      const end = view.coordsAtPos(to);
      const editorRect = view.dom.getBoundingClientRect();

      // 工具栏显示在选区上方中心位置
      const toolbarWidth = 300; // 估计宽度
      const left = Math.max(
        editorRect.left,
        Math.min(
          (start.left + end.left) / 2 - toolbarWidth / 2,
          editorRect.right - toolbarWidth
        )
      );
      const top = start.top - 48; // 工具栏高度 + 间距

      // 如果上方空间不够，显示在下方
      const finalTop = top < editorRect.top ? end.bottom + 8 : top;

      useEditorStore.getState().showFloatingToolbar({ top: finalTop, left });
    };

    // 使用 setTimeout 确保选区更新后再计算位置
    const handleSelectionChange = () => {
      setTimeout(updateToolbar, 0);
    };

    // 监听编辑器事件
    const dom = view.dom;
    dom.addEventListener('mouseup', handleSelectionChange);
    dom.addEventListener('keyup', handleSelectionChange);

    return () => {
      dom.removeEventListener('mouseup', handleSelectionChange);
      dom.removeEventListener('keyup', handleSelectionChange);
    };
  }, [view, hideFloatingToolbar]);

  // 点击外部隐藏
  useEffect(() => {
    if (!isFloatingToolbarVisible) return;

    const handleClickOutside = (e: MouseEvent) => {
      if (toolbarRef.current && !toolbarRef.current.contains(e.target as Node)) {
        // 不要立即隐藏，让选区处理逻辑来决定
      }
    };

    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, [isFloatingToolbarVisible]);

  if (!isFloatingToolbarVisible || !floatingToolbarPosition) return null;

  return (
    <div
      ref={toolbarRef}
      className={cn(
        'floating-toolbar',
        'fixed z-50 flex items-center gap-0.5 rounded-lg border border-gray-200 bg-white px-1 py-1 shadow-lg',
        className
      )}
      style={{
        top: floatingToolbarPosition.top,
        left: floatingToolbarPosition.left,
      }}
    >
      {toolbarButtons.map((button) => {
        const Icon = button.icon;
        const isActive = isMarkActive(button.markName);

        return (
          <button
            key={button.name}
            type="button"
            title={button.title}
            onClick={() => toggleMarkAction(button.markName)}
            className={cn(
              'flex h-8 w-8 items-center justify-center rounded-md transition-colors',
              isActive
                ? 'bg-blue-100 text-blue-700'
                : 'text-gray-600 hover:bg-gray-100 hover:text-gray-900'
            )}
          >
            <Icon className="h-4 w-4" />
          </button>
        );
      })}
    </div>
  );
}

export default FloatingToolbar;
