import React, { useState, useEffect, useRef } from 'react'
import { Copy, Check, ChevronDown } from 'lucide-react'
import type { ProgressState, ImportResult } from '../../hooks/useProgressCommand'

interface ImportProgressModalProps {
  isOpen: boolean
  isExecuting: boolean
  progress: ProgressState | null
  result: ImportResult | null
  logs: string[]
  onClose: () => void
}

export const ImportProgressModal: React.FC<ImportProgressModalProps> = ({
  isOpen,
  isExecuting,
  progress,
  result,
  logs,
  onClose
}) => {
  const [isCopied, setIsCopied] = useState(false)
  const [showCopyOptions, setShowCopyOptions] = useState(false)
  const dropdownRef = useRef<HTMLDivElement>(null)

  // 点击外部关闭下拉菜单
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
        setShowCopyOptions(false)
      }
    }

    if (showCopyOptions) {
      document.addEventListener('mousedown', handleClickOutside)
    }

    return () => {
      document.removeEventListener('mousedown', handleClickOutside)
    }
  }, [showCopyOptions])

  // 复制日志到剪贴板（详细格式）
  const copyLogsToClipboard = async (detailed: boolean = true) => {
    try {
      let logsText: string

      if (detailed) {
        // 构建详细的日志信息
        const timestamp = new Date().toLocaleString()
        const progressInfo = progress ? `当前进度: ${progress.step} - ${progress.message} (${progress.progress >= 0 ? progress.progress.toFixed(1) + '%' : '处理中'})` : ''
        const resultInfo = result ? `导入结果: ${result.status ? '成功' : '失败'} - ${result.msg}${result.imported_count > 0 ? ` (成功导入 ${result.imported_count} 个模板)` : ''}${result.failed_count > 0 ? ` (失败 ${result.failed_count} 个模板)` : ''}` : ''

        const header = [
          '=== 模板导入日志 ===',
          `导出时间: ${timestamp}`,
          progressInfo,
          resultInfo,
          '=== 详细日志 ===',
          ''
        ].filter(Boolean).join('\n')

        logsText = header + logs.join('\n')
      } else {
        // 简单格式，只复制日志内容
        logsText = logs.join('\n')
      }

      await navigator.clipboard.writeText(logsText)
      setIsCopied(true)
      setTimeout(() => setIsCopied(false), 2000) // 2秒后重置状态
    } catch (error) {
      console.error('复制日志失败:', error)
      // 如果剪贴板API失败，尝试使用传统方法
      try {
        const textArea = document.createElement('textarea')
        textArea.value = logs.join('\n')
        document.body.appendChild(textArea)
        textArea.select()
        document.execCommand('copy')
        document.body.removeChild(textArea)
        setIsCopied(true)
        setTimeout(() => setIsCopied(false), 2000)
      } catch (fallbackError) {
        console.error('备用复制方法也失败:', fallbackError)
      }
    }
  }

  if (!isOpen) return null

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50">
      <div className="bg-white rounded-lg max-w-2xl w-full max-h-[80vh] overflow-hidden">
        <div className="p-6">
          <div className="flex items-center justify-between mb-4">
            <h2 className="text-xl font-bold text-gray-900">模板导入进度</h2>
            {!isExecuting && (
              <button
                onClick={onClose}
                className="text-gray-400 hover:text-gray-600"
              >
                ×
              </button>
            )}
          </div>

          {/* Progress Bar */}
          {progress && (
            <div className="mb-4">
              <div className="flex justify-between mb-2">
                <span className="text-sm font-medium text-gray-700">{progress.step}</span>
                <span className="text-sm text-gray-500">
                  {progress.progress >= 0 ? `${progress.progress.toFixed(1)}%` : '处理中...'}
                </span>
              </div>
              <div className="w-full bg-gray-200 rounded-full h-2">
                <div
                  className="bg-blue-600 h-2 rounded-full transition-all duration-300"
                  style={{ width: `${Math.max(0, progress.progress)}%` }}
                ></div>
              </div>
              <p className="text-sm text-gray-600 mt-2">{progress.message}</p>
              {progress.details?.processed_templates !== undefined && progress.details?.total_templates !== undefined && (
                <p className="text-xs text-gray-500 mt-1">
                  已处理: {progress.details.processed_templates} / {progress.details.total_templates}
                </p>
              )}
            </div>
          )}

          {/* Import Result */}
          {result && (
            <div className={`mb-4 p-4 rounded-lg ${result.status ? 'bg-green-50 border border-green-200' : 'bg-red-50 border border-red-200'}`}>
              <div className="flex items-center justify-between">
                <div>
                  <h3 className={`font-medium ${result.status ? 'text-green-800' : 'text-red-800'}`}>
                    导入结果
                  </h3>
                  <p className={`text-sm ${result.status ? 'text-green-600' : 'text-red-600'}`}>
                    {result.msg}
                  </p>
                  {result.imported_count > 0 && (
                    <p className="text-sm text-green-600 mt-1">
                      成功导入 {result.imported_count} 个模板
                    </p>
                  )}
                  {result.failed_count > 0 && (
                    <details className="mt-2">
                      <summary className="text-sm text-red-600 cursor-pointer">
                        {result.failed_count} 个模板导入失败 (点击查看详情)
                      </summary>
                      <div className="mt-2 space-y-1">
                        {result.failed_templates.map((failed: any, index: number) => (
                          <div key={index} className="text-xs text-red-500">
                            {failed.name}: {failed.error}
                          </div>
                        ))}
                      </div>
                    </details>
                  )}
                </div>
              </div>
            </div>
          )}

          {/* Logs */}
          <div className="bg-gray-50 rounded-lg p-4 h-64 overflow-y-auto">
            <div className="flex items-center justify-between mb-2">
              <h4 className="font-medium text-gray-900">导入日志</h4>
              {logs.length > 0 && (
                <div className="relative">
                  <div className="flex items-center gap-1">
                    {/* 主复制按钮 */}
                    <button
                      onClick={() => copyLogsToClipboard(true)}
                      className="flex items-center gap-1 px-2 py-1 text-xs bg-gray-200 hover:bg-gray-300 text-gray-700 rounded-l transition-colors"
                      title="复制详细日志"
                    >
                      {isCopied ? (
                        <>
                          <Check size={12} />
                          已复制
                        </>
                      ) : (
                        <>
                          <Copy size={12} />
                          复制日志
                        </>
                      )}
                    </button>

                    {/* 下拉菜单按钮 */}
                    <div className="relative" ref={dropdownRef}>
                      <button
                        onClick={() => setShowCopyOptions(!showCopyOptions)}
                        className="flex items-center px-1 py-1 text-xs bg-gray-200 hover:bg-gray-300 text-gray-700 rounded-r border-l border-gray-300 transition-colors"
                        title="更多复制选项"
                      >
                        <ChevronDown size={12} />
                      </button>

                      {/* 下拉菜单 */}
                      {showCopyOptions && (
                        <div className="absolute right-0 top-full mt-1 bg-white border border-gray-200 rounded-md shadow-lg z-10 min-w-32">
                          <button
                            onClick={() => {
                              copyLogsToClipboard(true)
                              setShowCopyOptions(false)
                            }}
                            className="w-full text-left px-3 py-2 text-xs text-gray-700 hover:bg-gray-50 transition-colors"
                          >
                            复制详细日志
                          </button>
                          <button
                            onClick={() => {
                              copyLogsToClipboard(false)
                              setShowCopyOptions(false)
                            }}
                            className="w-full text-left px-3 py-2 text-xs text-gray-700 hover:bg-gray-50 transition-colors"
                          >
                            仅复制日志内容
                          </button>
                        </div>
                      )}
                    </div>
                  </div>
                </div>
              )}
            </div>
            <div className="space-y-1">
              {logs.length > 0 ? (
                logs.map((log, index) => (
                  <div key={index} className="text-xs text-gray-600 font-mono">
                    {log}
                  </div>
                ))
              ) : (
                <div className="text-xs text-gray-400 italic">
                  暂无日志信息
                </div>
              )}
            </div>
          </div>

          {/* Actions */}
          <div className="flex justify-end mt-4">
            {!isExecuting && (
              <button
                onClick={onClose}
                className="px-4 py-2 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300 transition-colors"
              >
                关闭
              </button>
            )}
          </div>
        </div>
      </div>
    </div>
  )
}
