import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import FileSelector from '../../src/components/FileSelector';

// 完整的mock响应对象
const createMockResponse = (status: number, data?: any) => ({
  status,
  ok: status >= 200 && status < 300,
  body: null,
  bodyUsed: false,
  statusText: status === 200 ? 'OK' : status === 201 ? 'Created' : status === 204 ? 'No Content' : 'Error',
  headers: new Headers(),
  url: '',
  redirected: false,
  type: 'basic' as ResponseType,
  json: async () => data || {},
  text: async () => '',
  blob: async () => new Blob(),
  arrayBuffer: async () => new ArrayBuffer(0),
  formData: async () => new FormData(),
  clone: function() { return this; }
});

// Mock API客户端
vi.mock('../../src/api/fileClient', () => {
  const mockFileClient = {
    index: {
      $get: vi.fn(() => Promise.resolve(createMockResponse(200, {
        data: [],
        pagination: { current: 1, pageSize: 50, total: 0 }
      }))),
    },
    ':id': {
      $get: vi.fn(() => Promise.resolve(createMockResponse(200, {}))),
    },
  };

  const mockFileClientManager = {
    get: vi.fn(() => mockFileClient),
  };

  return {
    fileClientManager: mockFileClientManager,
    fileClient: mockFileClient,
  };
});

// Mock 文件上传组件
vi.mock('../../src/components/MinioUploader', () => ({
  default: () => <div data-testid="minio-uploader">MinioUploader</div>,
}));

describe('FileSelector', () => {
  let queryClient: QueryClient;

  beforeEach(() => {
    queryClient = new QueryClient({
      defaultOptions: {
        queries: { retry: false },
        mutations: { retry: false },
      },
    });

    vi.clearAllMocks();
  });

  const renderWithQueryClient = (component: React.ReactElement) => {
    return render(
      <QueryClientProvider client={queryClient}>
        {component}
      </QueryClientProvider>
    );
  };

  const mockFiles = [
    {
      id: 1,
      name: 'test-image.jpg',
      type: 'image/jpeg',
      size: 1024,
      fullUrl: 'http://example.com/test-image.jpg',
      uploadTime: '2024-01-01T00:00:00Z',
    },
    {
      id: 2,
      name: 'test-document.pdf',
      type: 'application/pdf',
      size: 2048,
      fullUrl: 'http://example.com/test-document.pdf',
      uploadTime: '2024-01-01T00:00:00Z',
    },
  ];

  it('应该渲染文件选择器', () => {
    renderWithQueryClient(
      <FileSelector value={null} onChange={() => {}} />
    );

    expect(screen.getByTestId('file-selector-button')).toBeInTheDocument();
  });

  it('应该打开选择对话框', async () => {
    const { fileClient } = await import('../../src/api/fileClient');
    (fileClient.index.$get as any).mockResolvedValue(createMockResponse(200, {
      data: mockFiles,
      pagination: { current: 1, pageSize: 50, total: 2 }
    }));

    renderWithQueryClient(
      <FileSelector value={null} onChange={() => {}} />
    );

    const selectButton = screen.getByTestId('file-selector-button');
    fireEvent.click(selectButton);

    await waitFor(() => {
      expect(screen.getByTestId('file-selector-dialog')).toBeInTheDocument();
      expect(screen.getByRole('heading', { name: '选择文件' })).toBeInTheDocument();
      expect(screen.getByText('上传新文件或从已有文件中选择')).toBeInTheDocument();
    });
  });

  it('应该显示已选文件预览', async () => {
    const { fileClient } = await import('../../src/api/fileClient');
    (fileClient[':id'].$get as any).mockResolvedValue(createMockResponse(200, mockFiles[0]));

    renderWithQueryClient(
      <FileSelector value={1} onChange={() => {}} showPreview={true} />
    );

    await waitFor(() => {
      expect(screen.getByText('更换文件')).toBeInTheDocument();
    });
  });

  it('应该支持多选模式', async () => {
    const { fileClient } = await import('../../src/api/fileClient');
    (fileClient.index.$get as any).mockResolvedValue(createMockResponse(200, {
      data: mockFiles,
      pagination: { current: 1, pageSize: 50, total: 2 }
    }));

    const onChange = vi.fn();
    renderWithQueryClient(
      <FileSelector
        value={[1, 2]}
        onChange={onChange}
        allowMultiple={true}
        showPreview={true}
      />
    );

    await waitFor(() => {
      expect(screen.getByText('已选择 2 个文件')).toBeInTheDocument();
    });
  });

  it('应该过滤文件类型', async () => {
    const { fileClient } = await import('../../src/api/fileClient');
    (fileClient.index.$get as any).mockResolvedValue(createMockResponse(200, {
      data: mockFiles,
      pagination: { current: 1, pageSize: 50, total: 2 }
    }));

    renderWithQueryClient(
      <FileSelector
        value={null}
        onChange={() => {}}
        filterType="image"
      />
    );

    const selectButton = screen.getByTestId('file-selector-button');
    fireEvent.click(selectButton);

    await waitFor(() => {
      expect(fileClient.index.$get).toHaveBeenCalledWith({
        query: {
          page: 1,
          pageSize: 50,
          keyword: 'image'
        }
      });
    });
  });

  it('应该处理文件选择确认', async () => {
    const { fileClient } = await import('../../src/api/fileClient');
    (fileClient.index.$get as any).mockResolvedValue(createMockResponse(200, {
      data: mockFiles,
      pagination: { current: 1, pageSize: 50, total: 2 }
    }));

    const onChange = vi.fn();
    renderWithQueryClient(
      <FileSelector value={null} onChange={onChange} />
    );

    const selectButton = screen.getByTestId('file-selector-button');
    fireEvent.click(selectButton);

    await waitFor(() => {
      const fileItems = screen.getAllByText('test-image.jpg');
      fireEvent.click(fileItems[0]);
    });

    const confirmButton = screen.getByText('确认选择');
    fireEvent.click(confirmButton);

    expect(onChange).toHaveBeenCalledWith(1);
  });
});