'use client';

/**
 * LinkEditor Component
 * 链接编辑器组件 - 用于创建和编辑链接
 */

import React, { useEffect, useRef, useState, useCallback } from 'react';
import { useEditorStore } from '../../stores/useEditorStore';
import { cn } from '@/lib/utils';
import { Link2, ExternalLink, Trash2, Check, X } from 'lucide-react';
import { useTranslation } from '@/hooks/useTranslation';

export interface LinkEditorProps {
  className?: string;
}

export function LinkEditor({ className }: LinkEditorProps) {
  const { t } = useTranslation();
  const { view, isLinkEditorOpen, linkEditorPosition, linkEditorData, closeLinkEditor } =
    useEditorStore();
  const containerRef = useRef<HTMLDivElement>(null);
  const inputRef = useRef<HTMLInputElement>(null);
  const [url, setUrl] = useState('');
  const [text, setText] = useState('');

  // 同步初始数据
  useEffect(() => {
    if (isLinkEditorOpen && linkEditorData) {
      setUrl(linkEditorData.href || '');
      setText(linkEditorData.text || '');
    } else {
      setUrl('');
      setText('');
    }
  }, [isLinkEditorOpen, linkEditorData]);

  // 聚焦输入框
  useEffect(() => {
    if (isLinkEditorOpen && inputRef.current) {
      inputRef.current.focus();
      inputRef.current.select();
    }
  }, [isLinkEditorOpen]);

  // 应用链接
  const applyLink = useCallback(() => {
    if (!view || !url.trim()) return;

    const { state, dispatch } = view;
    const { from, to } = state.selection;
    const linkMark = state.schema.marks.link;

    if (!linkMark) {
      closeLinkEditor();
      return;
    }

    // 格式化 URL
    let formattedUrl = url.trim();
    if (!/^https?:\/\//i.test(formattedUrl) && !formattedUrl.startsWith('mailto:')) {
      formattedUrl = `https://${formattedUrl}`;
    }

    // 创建链接标记
    const mark = linkMark.create({ href: formattedUrl });

    if (linkEditorData?.from !== undefined && linkEditorData?.to !== undefined) {
      // 编辑现有链接
      const tr = state.tr
        .removeMark(linkEditorData.from, linkEditorData.to, linkMark)
        .addMark(linkEditorData.from, linkEditorData.to, mark);
      dispatch(tr);
    } else if (from !== to) {
      // 选中文本添加链接
      const tr = state.tr.addMark(from, to, mark);
      dispatch(tr);
    } else if (text.trim()) {
      // 插入带链接的文本
      const textNode = state.schema.text(text.trim(), [mark]);
      const tr = state.tr.replaceSelectionWith(textNode, false);
      dispatch(tr);
    }

    closeLinkEditor();
    view.focus();
  }, [view, url, text, linkEditorData, closeLinkEditor]);

  // 移除链接
  const removeLink = useCallback(() => {
    if (!view || !linkEditorData?.from || !linkEditorData?.to) return;

    const { state, dispatch } = view;
    const linkMark = state.schema.marks.link;

    if (linkMark) {
      const tr = state.tr.removeMark(linkEditorData.from, linkEditorData.to, linkMark);
      dispatch(tr);
    }

    closeLinkEditor();
    view.focus();
  }, [view, linkEditorData, closeLinkEditor]);

  // 键盘事件
  const handleKeyDown = useCallback(
    (e: React.KeyboardEvent) => {
      if (e.key === 'Enter') {
        e.preventDefault();
        applyLink();
      } else if (e.key === 'Escape') {
        e.preventDefault();
        closeLinkEditor();
        view?.focus();
      }
    },
    [applyLink, closeLinkEditor, view]
  );

  // 点击外部关闭
  useEffect(() => {
    if (!isLinkEditorOpen) return;

    const handleClickOutside = (e: MouseEvent) => {
      if (containerRef.current && !containerRef.current.contains(e.target as Node)) {
        closeLinkEditor();
      }
    };

    // 延迟添加监听器，避免触发立即关闭
    const timer = setTimeout(() => {
      document.addEventListener('mousedown', handleClickOutside);
    }, 100);

    return () => {
      clearTimeout(timer);
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, [isLinkEditorOpen, closeLinkEditor]);

  if (!isLinkEditorOpen || !linkEditorPosition) return null;

  const isEditing = !!linkEditorData?.href;

  return (
    <div
      ref={containerRef}
      className={cn(
        'link-editor',
        'fixed z-50 w-80 rounded-lg border border-gray-200 bg-white p-3 shadow-lg',
        className
      )}
      style={{
        top: linkEditorPosition.top,
        left: linkEditorPosition.left,
      }}
      onKeyDown={handleKeyDown}
    >
      {/* URL 输入 */}
      <div className="mb-3">
        <label className="mb-1.5 block text-xs font-medium text-gray-600">
          {t.documentEditor.linkEditor.urlLabel}
        </label>
        <div className="relative">
          <Link2 className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400" />
          <input
            ref={inputRef}
            type="url"
            value={url}
            onChange={(e) => setUrl(e.target.value)}
            placeholder={t.documentEditor.linkEditor.urlPlaceholder}
            className="w-full rounded-md border border-gray-200 bg-gray-50 py-2 pl-9 pr-3 text-sm outline-none transition-colors focus:border-blue-500 focus:bg-white focus:ring-1 focus:ring-blue-500"
          />
        </div>
      </div>

      {/* 文本输入（仅在新建链接且无选中文本时显示） */}
      {!isEditing && !linkEditorData?.text && (
        <div className="mb-3">
          <label className="mb-1.5 block text-xs font-medium text-gray-600">
            {t.documentEditor.linkEditor.textLabel}
          </label>
          <input
            type="text"
            value={text}
            onChange={(e) => setText(e.target.value)}
            placeholder={t.documentEditor.linkEditor.textPlaceholder}
            className="w-full rounded-md border border-gray-200 bg-gray-50 px-3 py-2 text-sm outline-none transition-colors focus:border-blue-500 focus:bg-white focus:ring-1 focus:ring-blue-500"
          />
        </div>
      )}

      {/* 操作按钮 */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-1">
          {isEditing && url && (
            <a
              href={url}
              target="_blank"
              rel="noopener noreferrer"
              className="flex items-center gap-1 rounded-md px-2 py-1.5 text-xs text-gray-500 hover:bg-gray-100 hover:text-gray-700"
            >
              <ExternalLink className="h-3.5 w-3.5" />
              {t.documentEditor.linkEditor.open}
            </a>
          )}
          {isEditing && (
            <button
              type="button"
              onClick={removeLink}
              className="flex items-center gap-1 rounded-md px-2 py-1.5 text-xs text-red-500 hover:bg-red-50"
            >
              <Trash2 className="h-3.5 w-3.5" />
              {t.documentEditor.linkEditor.remove}
            </button>
          )}
        </div>
        <div className="flex items-center gap-2">
          <button
            type="button"
            onClick={() => {
              closeLinkEditor();
              view?.focus();
            }}
            className="flex items-center gap-1 rounded-md px-3 py-1.5 text-xs text-gray-600 hover:bg-gray-100"
          >
            <X className="h-3.5 w-3.5" />
            {t.documentEditor.linkEditor.cancel}
          </button>
          <button
            type="button"
            onClick={applyLink}
            disabled={!url.trim()}
            className="flex items-center gap-1 rounded-md bg-blue-500 px-3 py-1.5 text-xs text-white hover:bg-blue-600 disabled:cursor-not-allowed disabled:opacity-50"
          >
            <Check className="h-3.5 w-3.5" />
            {t.documentEditor.linkEditor.confirm}
          </button>
        </div>
      </div>
    </div>
  );
}

export default LinkEditor;
