/**
 * 测试 ImportProgressModal 组件的复制功能
 */

import React from 'react'
import { render, screen, fireEvent, waitFor } from '@testing-library/react'
import { ImportProgressModal } from './ImportProgressModal'
import type { ProgressState, ImportResult } from '../../hooks/useProgressCommand'

// Mock clipboard API
const mockWriteText = jest.fn()
Object.assign(navigator, {
  clipboard: {
    writeText: mockWriteText,
  },
})

describe('ImportProgressModal', () => {
  const defaultProps = {
    isOpen: true,
    isExecuting: false,
    progress: null,
    result: null,
    logs: ['日志行1', '日志行2', '日志行3'],
    onClose: jest.fn(),
  }

  beforeEach(() => {
    mockWriteText.mockClear()
  })

  it('应该显示复制按钮当有日志时', () => {
    render(<ImportProgressModal {...defaultProps} />)
    
    expect(screen.getByTitle('复制详细日志')).toBeInTheDocument()
    expect(screen.getByTitle('更多复制选项')).toBeInTheDocument()
  })

  it('应该隐藏复制按钮当没有日志时', () => {
    render(<ImportProgressModal {...defaultProps} logs={[]} />)
    
    expect(screen.queryByTitle('复制详细日志')).not.toBeInTheDocument()
    expect(screen.queryByTitle('更多复制选项')).not.toBeInTheDocument()
  })

  it('应该复制详细日志格式', async () => {
    const progress: ProgressState = {
      step: '导入模板',
      progress: 50,
      message: '正在处理...',
      details: {},
      timestamp: Date.now()
    }

    const result: ImportResult = {
      status: true,
      msg: '导入成功',
      imported_count: 2,
      failed_count: 0,
      imported_templates: [],
      failed_templates: []
    }

    render(
      <ImportProgressModal 
        {...defaultProps} 
        progress={progress}
        result={result}
      />
    )
    
    const copyButton = screen.getByTitle('复制详细日志')
    fireEvent.click(copyButton)

    await waitFor(() => {
      expect(mockWriteText).toHaveBeenCalledWith(
        expect.stringContaining('=== 模板导入日志 ===')
      )
      expect(mockWriteText).toHaveBeenCalledWith(
        expect.stringContaining('当前进度: 导入模板')
      )
      expect(mockWriteText).toHaveBeenCalledWith(
        expect.stringContaining('导入结果: 成功')
      )
      expect(mockWriteText).toHaveBeenCalledWith(
        expect.stringContaining('日志行1')
      )
    })
  })

  it('应该显示下拉菜单选项', async () => {
    render(<ImportProgressModal {...defaultProps} />)
    
    const dropdownButton = screen.getByTitle('更多复制选项')
    fireEvent.click(dropdownButton)

    await waitFor(() => {
      expect(screen.getByText('复制详细日志')).toBeInTheDocument()
      expect(screen.getByText('仅复制日志内容')).toBeInTheDocument()
    })
  })

  it('应该复制简单日志格式', async () => {
    render(<ImportProgressModal {...defaultProps} />)
    
    const dropdownButton = screen.getByTitle('更多复制选项')
    fireEvent.click(dropdownButton)

    await waitFor(() => {
      const simpleButton = screen.getByText('仅复制日志内容')
      fireEvent.click(simpleButton)
    })

    await waitFor(() => {
      expect(mockWriteText).toHaveBeenCalledWith('日志行1\n日志行2\n日志行3')
    })
  })

  it('应该显示复制成功状态', async () => {
    render(<ImportProgressModal {...defaultProps} />)
    
    const copyButton = screen.getByTitle('复制详细日志')
    fireEvent.click(copyButton)

    await waitFor(() => {
      expect(screen.getByText('已复制')).toBeInTheDocument()
    })

    // 等待状态重置
    await waitFor(() => {
      expect(screen.getByText('复制日志')).toBeInTheDocument()
    }, { timeout: 3000 })
  })

  it('应该处理复制失败的情况', async () => {
    mockWriteText.mockRejectedValue(new Error('复制失败'))
    
    // Mock console.error to avoid test output noise
    const consoleSpy = jest.spyOn(console, 'error').mockImplementation()
    
    render(<ImportProgressModal {...defaultProps} />)
    
    const copyButton = screen.getByTitle('复制详细日志')
    fireEvent.click(copyButton)

    await waitFor(() => {
      expect(consoleSpy).toHaveBeenCalledWith('复制日志失败:', expect.any(Error))
    })

    consoleSpy.mockRestore()
  })

  it('应该在点击外部时关闭下拉菜单', async () => {
    render(<ImportProgressModal {...defaultProps} />)
    
    const dropdownButton = screen.getByTitle('更多复制选项')
    fireEvent.click(dropdownButton)

    await waitFor(() => {
      expect(screen.getByText('复制详细日志')).toBeInTheDocument()
    })

    // 点击外部
    fireEvent.mouseDown(document.body)

    await waitFor(() => {
      expect(screen.queryByText('复制详细日志')).not.toBeInTheDocument()
    })
  })

  it('应该显示暂无日志信息当日志为空时', () => {
    render(<ImportProgressModal {...defaultProps} logs={[]} />)
    
    expect(screen.getByText('暂无日志信息')).toBeInTheDocument()
  })

  it('应该正确格式化进度信息', async () => {
    const progress: ProgressState = {
      step: '扫描文件',
      progress: -1, // 不确定进度
      message: '正在扫描模板文件...',
      details: {
        processed_templates: 3,
        total_templates: 10
      },
      timestamp: Date.now()
    }

    render(
      <ImportProgressModal 
        {...defaultProps} 
        progress={progress}
      />
    )
    
    const copyButton = screen.getByTitle('复制详细日志')
    fireEvent.click(copyButton)

    await waitFor(() => {
      expect(mockWriteText).toHaveBeenCalledWith(
        expect.stringContaining('当前进度: 扫描文件 - 正在扫描模板文件... (处理中)')
      )
    })
  })

  it('应该正确格式化失败结果信息', async () => {
    const result: ImportResult = {
      status: false,
      msg: '导入失败',
      imported_count: 1,
      failed_count: 2,
      imported_templates: [],
      failed_templates: [
        { name: '模板1', error: '文件损坏' },
        { name: '模板2', error: '格式错误' }
      ]
    }

    render(
      <ImportProgressModal 
        {...defaultProps} 
        result={result}
      />
    )
    
    const copyButton = screen.getByTitle('复制详细日志')
    fireEvent.click(copyButton)

    await waitFor(() => {
      expect(mockWriteText).toHaveBeenCalledWith(
        expect.stringContaining('导入结果: 失败 - 导入失败 (成功导入 1 个模板) (失败 2 个模板)')
      )
    })
  })
})
