/**
 * ProjectMaterialsCenter 组件测试
 * 验证修复后的分类加载功能
 */

import React from 'react'
import { render, screen, waitFor } from '@testing-library/react'
import '@testing-library/jest-dom'
import ProjectMaterialsCenter from './ProjectMaterialsCenter'
import { ResourceCategoryServiceV2 } from '../services/resourceCategoryServiceV2'

// Mock 服务
jest.mock('../services/resourceCategoryServiceV2')
jest.mock('../services/mediaService')
jest.mock('./VideoPlayer', () => ({ isOpen, onClose }: any) => 
  isOpen ? <div data-testid="video-player">Video Player</div> : null
)
jest.mock('./ImportMaterialModal', () => ({ onCancel }: any) => 
  <div data-testid="import-modal">Import Modal</div>
)
jest.mock('./VideoPlayer2', () => ({ src }: any) => 
  <div data-testid="video-player2">Video Player 2: {src}</div>
)

const mockResourceCategoryService = ResourceCategoryServiceV2 as jest.Mocked<typeof ResourceCategoryServiceV2>

describe('ProjectMaterialsCenter', () => {
  const mockProject = {
    id: 'test-project',
    product_name: 'Test Product',
    description: 'Test Description',
    created_at: '2024-01-01',
    updated_at: '2024-01-01'
  }

  const mockMaterials = [
    {
      id: 'material-1',
      filename: 'test-video.mp4',
      file_path: '/path/to/video.mp4',
      thumbnail_path: '/path/to/thumb.jpg',
      duration: 120,
      file_size: 1024000,
      tags: ['Test Product', '原始'],
      use_count: 0,
      segment_index: 0,
      project_id: 'test-project',
      created_at: '2024-01-01',
      updated_at: '2024-01-01'
    }
  ]

  const mockModels = [
    {
      id: 'model-1',
      model_number: 'M001',
      name: 'Test Model',
      description: 'Test Model Description',
      created_at: '2024-01-01',
      updated_at: '2024-01-01'
    }
  ]

  const mockCategories = [
    {
      id: 'cat-1',
      title: '视频素材',
      ai_prompt: '用于识别视频文件',
      color: '#FF6B6B',
      is_active: true,
      is_cloud: false,
      user_id: 'test-user',
      created_at: '2024-01-01',
      updated_at: '2024-01-01'
    },
    {
      id: 'cat-2',
      title: '音频素材',
      ai_prompt: '用于识别音频文件',
      color: '#4ECDC4',
      is_active: false, // 这个分类应该被过滤掉
      is_cloud: false,
      user_id: 'test-user',
      created_at: '2024-01-01',
      updated_at: '2024-01-01'
    }
  ]

  beforeEach(() => {
    jest.clearAllMocks()
  })

  it('应该正确加载和过滤活跃的分类', async () => {
    // Mock 服务返回分类数据
    mockResourceCategoryService.getAllCategories.mockResolvedValue(mockCategories)

    render(
      <ProjectMaterialsCenter
        project={mockProject}
        materials={mockMaterials}
        models={mockModels}
        onMaterialsChange={jest.fn()}
      />
    )

    // 等待分类加载完成
    await waitFor(() => {
      expect(mockResourceCategoryService.getAllCategories).toHaveBeenCalled()
    })

    // 验证只显示活跃的分类
    expect(screen.getByText('视频素材 (1)')).toBeInTheDocument()
    expect(screen.queryByText('音频素材')).not.toBeInTheDocument()
  })

  it('应该正确处理分类加载失败的情况', async () => {
    // Mock 服务抛出错误
    mockResourceCategoryService.getAllCategories.mockRejectedValue(new Error('Network error'))

    const consoleSpy = jest.spyOn(console, 'error').mockImplementation()

    render(
      <ProjectMaterialsCenter
        project={mockProject}
        materials={mockMaterials}
        models={mockModels}
        onMaterialsChange={jest.fn()}
      />
    )

    // 等待错误处理完成
    await waitFor(() => {
      expect(consoleSpy).toHaveBeenCalledWith('Failed to load categories:', expect.any(Error))
    })

    // 验证显示全部分类选项（即使加载失败）
    expect(screen.getByText('全部 (1)')).toBeInTheDocument()

    consoleSpy.mockRestore()
  })

  it('应该正确计算分类的素材数量', async () => {
    mockResourceCategoryService.getAllCategories.mockResolvedValue(mockCategories)

    render(
      <ProjectMaterialsCenter
        project={mockProject}
        materials={mockMaterials}
        models={mockModels}
        onMaterialsChange={jest.fn()}
      />
    )

    await waitFor(() => {
      expect(mockResourceCategoryService.getAllCategories).toHaveBeenCalled()
    })

    // 验证分类数量计算正确
    expect(screen.getByText('全部 (1)')).toBeInTheDocument()
    expect(screen.getByText('视频素材 (1)')).toBeInTheDocument()
  })

  it('应该显示加载状态', () => {
    // Mock 一个永远不会 resolve 的 Promise 来模拟加载状态
    mockResourceCategoryService.getAllCategories.mockImplementation(
      () => new Promise(() => {}) // 永远不会 resolve
    )

    render(
      <ProjectMaterialsCenter
        project={mockProject}
        materials={mockMaterials}
        models={mockModels}
        onMaterialsChange={jest.fn()}
      />
    )

    // 验证显示加载状态
    expect(screen.getByText('加载中...')).toBeInTheDocument()
  })
})

// 集成测试：验证新的 API 调用方式
describe('ProjectMaterialsCenter API Integration', () => {
  it('应该使用新的 ResourceCategoryServiceV2 API', async () => {
    const mockCategories = [
      {
        id: 'cat-1',
        title: '测试分类',
        ai_prompt: '测试提示',
        color: '#FF0000',
        is_active: true,
        is_cloud: false,
        user_id: 'test-user',
        created_at: '2024-01-01',
        updated_at: '2024-01-01'
      }
    ]

    mockResourceCategoryService.getAllCategories.mockResolvedValue(mockCategories)

    const { rerender } = render(
      <ProjectMaterialsCenter
        project={{
          id: 'test',
          product_name: 'Test',
          description: 'Test',
          created_at: '2024-01-01',
          updated_at: '2024-01-01'
        }}
        materials={[]}
        models={[]}
        onMaterialsChange={jest.fn()}
      />
    )

    await waitFor(() => {
      expect(mockResourceCategoryService.getAllCategories).toHaveBeenCalledWith()
    })

    // 验证调用了正确的方法
    expect(mockResourceCategoryService.getAllCategories).toHaveBeenCalledTimes(1)
  })
})
