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 { GoodsCategoryManagement } from '../../src/components/GoodsCategoryManagement';
import { goodsCategoryClient } from '../../src/api/goodsCategoryClient';

// 完整的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 client
vi.mock('../../src/api/goodsCategoryClient', () => {
  const mockGoodsCategoryClient = {
    index: {
      $get: vi.fn(() => Promise.resolve({ status: 200, body: null })),
      $post: vi.fn(() => Promise.resolve({ status: 201, body: null })),
    },
    ':id': {
      $put: vi.fn(() => Promise.resolve({ status: 200, body: null })),
      $delete: vi.fn(() => Promise.resolve({ status: 204, body: null })),
    },
  };

  const mockGoodsCategoryClientManager = {
    get: vi.fn(() => mockGoodsCategoryClient),
  };

  return {
    goodsCategoryClientManager: mockGoodsCategoryClientManager,
    goodsCategoryClient: mockGoodsCategoryClient,
  };
});

// Mock toast
vi.mock('sonner', () => ({
  toast: {
    success: vi.fn(() => {}),
    error: vi.fn(() => {}),
  },
}));

// Mock FileSelector
vi.mock('@d8d/file-management-ui-mt', () => ({
  FileSelector: ({ value, onChange }: { value?: number; onChange?: (value: number) => void }) => (
    <div data-testid="file-selector">
      <button onClick={() => onChange?.(1)}>选择文件</button>
      <span>当前文件ID: {value}</span>
    </div>
  ),
}));

const createTestQueryClient = () =>
  new QueryClient({
    defaultOptions: {
      queries: {
        retry: false,
      },
    },
  });

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

describe('商品分类管理集成测试', () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it('应该完成完整的商品分类CRUD流程', async () => {
    const mockCategories = {
      data: [
        {
          id: 1,
          name: '电子产品',
          parentId: 0,
          imageFileId: null,
          level: 0,
          state: 1,
          createdAt: '2024-01-01T00:00:00Z',
          updatedAt: '2024-01-01T00:00:00Z',
          createdBy: 1,
          updatedBy: 1,
          imageFile: null,
        },
      ],
      pagination: {
        total: 1,
        page: 1,
        pageSize: 10,
      },
    };

    const { toast } = await import('sonner');

    // Mock initial category list
    (goodsCategoryClient.index.$get as any).mockResolvedValue(createMockResponse(200, mockCategories));

    renderWithProviders(<GoodsCategoryManagement />);

    // Wait for initial data to load
    await waitFor(() => {
      expect(screen.getByText('电子产品')).toBeInTheDocument();
    });

    // Test create category
    const createButton = screen.getByTestId('create-button');
    fireEvent.click(createButton);

    // Fill create form
    const nameInput = screen.getByPlaceholderText('请输入分类名称');
    const parentIdInput = screen.getByPlaceholderText('请输入上级分类ID，0表示顶级分类');
    const levelInput = screen.getByPlaceholderText('请输入层级');

    fireEvent.change(nameInput, { target: { value: '新分类' } });
    fireEvent.change(parentIdInput, { target: { value: '0' } });
    fireEvent.change(levelInput, { target: { value: '0' } });

    // Mock successful creation
    (goodsCategoryClient.index.$post as any).mockResolvedValue(createMockResponse(201, { id: 2, name: '新分类' }));

    const submitButton = screen.getByText('创建');
    fireEvent.click(submitButton);

    await waitFor(() => {
      expect(goodsCategoryClient.index.$post).toHaveBeenCalledWith({
        json: {
          name: '新分类',
          parentId: 0,
          imageFileId: null,
          level: 0,
          state: 1,
        },
      });
      expect(toast.success).toHaveBeenCalledWith('创建成功');
    });

    // Test edit category
    const editButton = screen.getByTestId('edit-button-1');
    fireEvent.click(editButton);

    // Verify edit form is populated
    await waitFor(() => {
      expect(screen.getByDisplayValue('电子产品')).toBeInTheDocument();
    });

    // Update category
    const updateNameInput = screen.getByDisplayValue('电子产品');
    fireEvent.change(updateNameInput, { target: { value: '更新后的分类' } });

    // Mock successful update
    (goodsCategoryClient[':id']['$put'] as any).mockResolvedValue(createMockResponse(200));

    const updateButton = screen.getByText('更新');
    fireEvent.click(updateButton);

    await waitFor(() => {
      expect(goodsCategoryClient[':id']['$put']).toHaveBeenCalledWith({
        param: { id: 1 },
        json: {
          name: '更新后的分类',
          parentId: 0,
          imageFileId: null,
          level: 0,
          state: 1,
        },
      });
      expect(toast.success).toHaveBeenCalledWith('更新成功');
    });

    // Test delete category
    const deleteButton = screen.getByTestId('delete-button-1');
    fireEvent.click(deleteButton);

    // Confirm deletion
    expect(screen.getByText('确认删除')).toBeInTheDocument();

    // Mock successful deletion
    (goodsCategoryClient[':id']['$delete'] as any).mockResolvedValue({
      status: 204,
    });

    const confirmDeleteButton = screen.getByText('删除');
    fireEvent.click(confirmDeleteButton);

    await waitFor(() => {
      expect(goodsCategoryClient[':id']['$delete']).toHaveBeenCalledWith({
        param: { id: 1 },
      });
      expect(toast.success).toHaveBeenCalledWith('删除成功');
    });
  });

  it('应该优雅处理API错误', async () => {
    const { goodsCategoryClient } = await import('../../src/api/goodsCategoryClient');
    const { toast } = await import('sonner');

    // Mock API error
    (goodsCategoryClient.index.$get as any).mockRejectedValue(new Error('API Error'));

    renderWithProviders(<GoodsCategoryManagement />);

    // Should handle error without crashing - 等待加载完成
    await waitFor(() => {
      expect(screen.getByText('商品分类管理')).toBeInTheDocument();
    });

    // 等待加载完成 - API错误后应该显示表格骨架屏
    await waitFor(() => {
      expect(screen.getByTestId('create-button')).toBeInTheDocument();
      expect(screen.getByTestId('search-input')).toBeInTheDocument();
    });

    // Test create category error
    const createButton = screen.getByTestId('create-button');
    fireEvent.click(createButton);

    const nameInput = screen.getByPlaceholderText('请输入分类名称');

    fireEvent.change(nameInput, { target: { value: '测试分类' } });

    // Mock creation error
    (goodsCategoryClient.index.$post as any).mockRejectedValue(new Error('Creation failed'));

    const submitButton = screen.getByText('创建');
    fireEvent.click(submitButton);

    await waitFor(() => {
      expect(toast.error).toHaveBeenCalledWith('创建失败，请重试');
    });
  });

  it('应该处理搜索功能', async () => {
    const { goodsCategoryClient } = await import('../../src/api/goodsCategoryClient');
    const mockCategories = {
      data: [],
      pagination: { total: 0, page: 1, pageSize: 10 },
    };

    (goodsCategoryClient.index.$get as any).mockResolvedValue(createMockResponse(200, mockCategories));

    renderWithProviders(<GoodsCategoryManagement />);

    // 等待数据加载完成
    await waitFor(() => {
      expect(screen.getByText('暂无数据')).toBeInTheDocument();
    });

    // Test search
    const searchInput = screen.getByTestId('search-input');
    fireEvent.change(searchInput, { target: { value: '搜索关键词' } });

    const searchButton = screen.getByText('搜索');
    fireEvent.click(searchButton);

    await waitFor(() => {
      expect(goodsCategoryClient.index.$get).toHaveBeenCalledWith({
        query: {
          page: 1,
          pageSize: 10,
          keyword: '搜索关键词',
          filters: expect.stringContaining('state'),
        },
      });
    });
  });

  it('应该显示分类状态和图片信息', async () => {
    const mockCategories = {
      data: [
        {
          id: 1,
          name: '可用分类',
          parentId: 0,
          imageFileId: 1,
          level: 0,
          state: 1,
          createdAt: '2024-01-01T00:00:00Z',
          updatedAt: '2024-01-01T00:00:00Z',
          createdBy: 1,
          updatedBy: 1,
          imageFile: {
            id: 1,
            fullUrl: 'http://example.com/image.jpg',
          },
        },
        {
          id: 2,
          name: '不可用分类',
          parentId: 0,
          imageFileId: null,
          level: 0,
          state: 2,
          createdAt: '2024-01-01T00:00:00Z',
          updatedAt: '2024-01-01T00:00:00Z',
          createdBy: 1,
          updatedBy: 1,
          imageFile: null,
        },
      ],
      pagination: {
        total: 2,
        page: 1,
        pageSize: 10,
      },
    };

    (goodsCategoryClient.index.$get as any).mockResolvedValue(createMockResponse(200, mockCategories));

    renderWithProviders(<GoodsCategoryManagement />);

    // Wait for data to load
    await waitFor(() => {
      expect(screen.getByText('可用分类')).toBeInTheDocument();
      expect(screen.getByText('不可用分类')).toBeInTheDocument();
    });

    // Verify status badges
    expect(screen.getByText('可用')).toBeInTheDocument();
    expect(screen.getByText('不可用')).toBeInTheDocument();

    // Verify image display
    expect(screen.getByAltText('可用分类')).toBeInTheDocument();
    expect(screen.getByText('无图片')).toBeInTheDocument();
  });
});