import { useLayoutEffect, useRef, useState, useCallback } from 'react';
import { useLanguage } from '../contexts/LanguageContext';

interface NotebookGlobalDragDropProps {
  onFilesSelected: (files: FileList) => void;
  isAdmin: boolean;
}

// 为笔记本组件也添加类似的控制
let isNotebookDragDropEnabled = true;

// 添加一个模块级变量来存储强制隐藏的回调函数
let notebookForceHideCallback: (() => void) | null = null;

export const setNotebookDragDropEnabled = (enabled: boolean) => {
  isNotebookDragDropEnabled = enabled;
  // 当禁用时,立即强制隐藏覆盖层
  if (!enabled && notebookForceHideCallback) {
    notebookForceHideCallback();
  }
};

export const NotebookGlobalDragDropOverlay: React.FC<NotebookGlobalDragDropProps> = ({ onFilesSelected, isAdmin }) => {
  const { t } = useLanguage();
  const overlayRef = useRef<HTMLDivElement>(null);
  const [isVisible, setIsVisible] = useState(false);
  const dragCounterRef = useRef(0);
  const isDragActiveRef = useRef(false);

  const hasFiles = useCallback((dt: DataTransfer | null) => {
    if (!dt) return false;

    // より厳格なチェック: typesにFilesが含まれることを確認
    const hasFileType = dt.types && dt.types.includes('Files');
    if (!hasFileType) return false;

    // itemsが存在する場合、実際にファイルがあるかチェック
    if (dt.items && dt.items.length > 0) {
      // 少なくとも1つのファイルアイテムがあることを確認
      for (let i = 0; i < dt.items.length; i++) {
        if (dt.items[i].kind === 'file') {
          return true;
        }
      }
      return false;
    }

    // itemsがない場合はtypesのみで判断(後方互換性)
    return hasFileType;
  }, []);

  const handleDragEnter = useCallback((e: DragEvent) => {
    // 如果拖放功能被禁用,则忽略事件
    if (!isNotebookDragDropEnabled) return;

    // 只有当数据传输包含文件时才处理
    if (!hasFiles(e.dataTransfer)) return;

    e.preventDefault();
    e.stopPropagation();

    dragCounterRef.current++;
    if (dragCounterRef.current === 1) {
      // 立即显示覆盖层,依赖强制隐藏机制来处理误触发
      setIsVisible(true);
      if (overlayRef.current) {
        overlayRef.current.style.opacity = '1';
        overlayRef.current.style.visibility = 'visible';
      }
      isDragActiveRef.current = true;
    }
  }, [hasFiles]);

  const handleDragOver = useCallback((e: DragEvent) => {
    // 如果拖放功能被禁用，则忽略事件
    if (!isNotebookDragDropEnabled) return;

    // 只有当数据传输包含文件时才处理
    if (!hasFiles(e.dataTransfer)) return;

    e.preventDefault();
    e.stopPropagation();
    e.dataTransfer!.dropEffect = 'copy';
  }, [hasFiles]);

  const handleDragLeave = useCallback((e: DragEvent) => {
    // 如果拖放功能被禁用，则忽略事件
    if (!isNotebookDragDropEnabled) return;

    // 只有当数据传输包含文件时才处理
    if (!hasFiles(e.dataTransfer)) return;

    e.preventDefault();
    e.stopPropagation();

    dragCounterRef.current = Math.max(0, dragCounterRef.current - 1);
    if (dragCounterRef.current === 0 && isDragActiveRef.current) {
      // 隐藏全局拖拽上传覆盖层
      if (overlayRef.current) {
        overlayRef.current.style.opacity = '0';
        overlayRef.current.style.visibility = 'hidden';
      }
      setIsVisible(false); // 通过状态控制隐藏
      isDragActiveRef.current = false;
    }
  }, [hasFiles]);

  const handleDrop = useCallback((e: DragEvent) => {
    // 如果拖放功能被禁用，则忽略事件
    if (!isNotebookDragDropEnabled) return;

    // 只有当数据传输包含文件时才处理
    if (!hasFiles(e.dataTransfer)) return;

    e.preventDefault();
    e.stopPropagation();
    dragCounterRef.current = 0;

    // 隐藏全局拖拽上传覆盖层
    if (overlayRef.current) {
      overlayRef.current.style.opacity = '0';
      overlayRef.current.style.visibility = 'hidden';
    }
    setIsVisible(false);

    isDragActiveRef.current = false;

    // 处理文件
    if (e.dataTransfer?.files && e.dataTransfer.files.length > 0) {
      onFilesSelected(e.dataTransfer.files);
    }
  }, [hasFiles, onFilesSelected]);

  useLayoutEffect(() => {
    if (!isAdmin) return;

    // 初始化时确保dragCounter和isDragActive为初始值
    dragCounterRef.current = 0;
    isDragActiveRef.current = false;

    // 注册强制隐藏回调
    notebookForceHideCallback = () => {
      dragCounterRef.current = 0;
      isDragActiveRef.current = false;
      setIsVisible(false);
      if (overlayRef.current) {
        overlayRef.current.style.opacity = '0';
        overlayRef.current.style.visibility = 'hidden';
      }
    };

    // 添加全局事件监听器
    document.addEventListener('dragenter', handleDragEnter);
    document.addEventListener('dragover', handleDragOver);
    document.addEventListener('dragleave', handleDragLeave);
    document.addEventListener('drop', handleDrop);

    // 清理函数
    return () => {
      document.removeEventListener('dragenter', handleDragEnter);
      document.removeEventListener('dragover', handleDragOver);
      document.removeEventListener('dragleave', handleDragLeave);
      document.removeEventListener('drop', handleDrop);

      // 清除回调引用
      notebookForceHideCallback = null;

      // 确保在组件卸载时重置状态和清除任何可能的显示
      dragCounterRef.current = 0;
      isDragActiveRef.current = false;
      if (overlayRef.current) {
        overlayRef.current.style.opacity = '0';
        overlayRef.current.style.visibility = 'hidden';
      }
      setIsVisible(false);
    };
  }, [isAdmin, handleDragEnter, handleDragOver, handleDragLeave, handleDrop]);

  // 添加运行时检查，确保只有在适当情况下才渲染
  if (!isAdmin || typeof window === 'undefined') {
    return null;
  }

  // 只有当 isVisible 为 true 时才渲染组件内容
  if (!isVisible) {
    return null;
  }

  return (
    <div
      ref={overlayRef}
      id="notebook-global-drag-overlay"
      className="fixed inset-0 bg-black bg-opacity-50 items-center justify-center z-50 transition-opacity duration-300 pointer-events-none"
      style={{ opacity: 1, visibility: 'visible', display: 'flex' }}
    >
      <div className="w-3/4 max-w-2xl pointer-events-auto">
        <div className="border-2 border-dashed border-blue-500 bg-blue-50 rounded-xl p-8 text-center cursor-pointer">
          <div className="flex flex-col items-center justify-center gap-6">
            <div className="p-4 bg-blue-100 rounded-full">
              <svg xmlns="http://www.w3.org/2000/svg" width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="w-10 h-10 text-blue-600">
                <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path>
                <polyline points="17 8 12 3 7 8"></polyline>
                <line x1="12" x2="12" y1="3" y2="15"></line>
              </svg>
            </div>
            <div className="space-y-2">
              <h3 className="text-lg font-semibold text-slate-700">
                {t('dragDropUploadTitle')}
              </h3>
              <p className="text-sm text-slate-500">
                {t('dragDropUploadDesc')}
              </p>
            </div>
            <div className="flex items-center gap-6 mt-2">
              <div className="flex items-center gap-2 text-xs text-slate-500 bg-white px-3 py-1.5 rounded-full border border-slate-200">
                <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="w-4 h-4">
                  <path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"></path>
                  <polyline points="14 2 14 8 20 8"></polyline>
                </svg>
                <span>{t('supportedFormats')}</span>
              </div>
              <div className="flex items-center gap-2 text-xs text-slate-500 bg-white px-3 py-1.5 rounded-full border border-slate-200">
                <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="w-4 h-4">
                  <rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect>
                  <circle cx="8.5" cy="8.5" r="1.5"></circle>
                  <path d="M21 15l-5-5L5 21"></path>
                </svg>
                <span>PDF, DOC, XLS, PPT, TXT, Images...</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};