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 { GoodsManagement } from '../../src/components/GoodsManagement';
import { goodsClient, goodsClientManager } from '../../src/api/goodsClient';

// 完整的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/goodsClient', () => {
  const mockGoodsClient = {
    $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 mockGoodsClientManager = {
    get: vi.fn(() => mockGoodsClient),
  };

  return {
    goodsClientManager: mockGoodsClientManager,
    goodsClient: mockGoodsClient,
  };
});

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

// Mock 文件选择器组件
vi.mock('@d8d/file-management-ui', () => ({
  FileSelector: ({ value, onChange, placeholder }: any) => (
    <button
      data-testid="file-selector"
      onClick={() => onChange?.(value || 1)}
    >
      {placeholder || '选择文件'}
    </button>
  ),
}));

// Mock 商品分类级联选择器
vi.mock('@d8d/goods-category-management-ui', () => ({
  GoodsCategoryCascadeSelector: ({ required }: any) => (
    <div data-testid="goods-category-cascade-selector">
      商品分类选择器 {required && <span>*</span>}
    </div>
  ),
}));

// Mock 供应商选择器
vi.mock('@d8d/supplier-management-ui', () => ({
  SupplierSelector: ({ value, onChange }: any) => (
    <select
      data-testid="supplier-selector"
      value={value || ''}
      onChange={(e) => onChange?.(e.target.value ? Number(e.target.value) : null)}
    >
      <option value="">选择供应商</option>
      <option value="1">供应商1</option>
      <option value="2">供应商2</option>
    </select>
  ),
}));

// Mock 商户选择器
vi.mock('@d8d/merchant-management-ui', () => ({
  MerchantSelector: ({ value, onChange }: any) => (
    <select
      data-testid="merchant-selector"
      value={value || ''}
      onChange={(e) => onChange?.(e.target.value ? Number(e.target.value) : null)}
    >
      <option value="">选择商户</option>
      <option value="1">商户1</option>
      <option value="2">商户2</option>
    </select>
  ),
}));

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 mockGoods = {
      data: [
        {
          id: 1,
          name: '测试商品',
          price: 99.99,
          costPrice: 50.00,
          categoryId1: 1,
          categoryId2: 2,
          categoryId3: 3,
          goodsType: 1,
          supplierId: 1,
          merchantId: 1,
          imageFileId: 1,
          slideImageIds: [1, 2],
          detail: '商品详情',
          instructions: '商品简介',
          sort: 0,
          state: 1,
          stock: 100,
          lowestBuy: 1,
          salesNum: 50,
          createdAt: '2024-01-01T00:00:00Z',
          updatedAt: '2024-01-01T00:00:00Z',
          createdBy: 1,
          updatedBy: 1,
          category1: { id: 1, name: '一级分类' },
          category2: { id: 2, name: '二级分类' },
          category3: { id: 3, name: '三级分类' },
          supplier: { id: 1, name: '供应商1' },
          merchant: { id: 1, name: '商户1', username: 'merchant1' },
          imageFile: { id: 1, fullUrl: 'http://example.com/image.jpg' },
          slideImages: [
            { id: 1, fullUrl: 'http://example.com/slide1.jpg' },
            { id: 2, fullUrl: 'http://example.com/slide2.jpg' }
          ],
        },
      ],
      pagination: {
        total: 1,
        page: 1,
        pageSize: 10,
      },
    };

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

    // Mock initial goods list
    (goodsClientManager.get().$get as any).mockResolvedValue(createMockResponse(200, mockGoods));

    renderWithProviders(<GoodsManagement />);

    // Wait for initial data to load
    await waitFor(() => {
      expect(screen.getByText('测试商品')).toBeInTheDocument();
    });

    // Test create goods
    const createButton = screen.getByText('创建商品');
    fireEvent.click(createButton);

    // Fill create form
    const nameInput = screen.getByTestId('goods-name-input');
    const priceInput = screen.getByTestId('goods-price-input');
    const costPriceInput = screen.getByTestId('goods-cost-price-input');
    const stockInput = screen.getByTestId('goods-stock-input');

    fireEvent.change(nameInput, { target: { value: '新商品' } });
    fireEvent.change(priceInput, { target: { value: '199.99' } });
    fireEvent.change(costPriceInput, { target: { value: '100.00' } });
    fireEvent.change(stockInput, { target: { value: '50' } });

    // Select supplier and merchant
    const supplierSelect = screen.getByTestId('supplier-selector');
    const merchantSelect = screen.getByTestId('merchant-selector');
    fireEvent.change(supplierSelect, { target: { value: '1' } });
    fireEvent.change(merchantSelect, { target: { value: '1' } });

    // Select file
    const fileSelectors = screen.getAllByTestId('file-selector');
    // 只有2个文件选择器：主图和轮播图
    fireEvent.click(fileSelectors[0]); // 主图
    fireEvent.click(fileSelectors[1]); // 轮播图

    // Mock successful creation
    (goodsClient.$post as any).mockResolvedValue(createMockResponse(201, { id: 2, name: '新商品' }));

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

    await waitFor(() => {
      expect(goodsClient.$post).toHaveBeenCalled();
      expect(toast.success).toHaveBeenCalledWith('商品创建成功');
    });

    // Test edit goods
    const editButtons = screen.getAllByTestId('edit-goods-button');
    fireEvent.click(editButtons[0]);

    // Verify edit form is populated
    await waitFor(() => {
      expect(screen.getByDisplayValue('测试商品')).toBeInTheDocument();
    });

    // Update goods
    const updateNameInput = screen.getByDisplayValue('测试商品');
    fireEvent.change(updateNameInput, { target: { value: '更新后的商品' } });

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

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

    await waitFor(() => {
      expect(goodsClient[':id']['$put']).toHaveBeenCalled();
      expect(toast.success).toHaveBeenCalledWith('商品更新成功');
    });

    // Test delete goods
    const deleteButtons = screen.getAllByTestId('delete-goods-button');
    fireEvent.click(deleteButtons[0]);

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

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

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

    await waitFor(() => {
      expect(goodsClient[':id']['$delete']).toHaveBeenCalled();
      expect(toast.success).toHaveBeenCalledWith('商品删除成功');
    });
  });

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

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

    // Render component and verify it doesn't crash
    renderWithProviders(<GoodsManagement />);

    // Verify component renders without crashing
    await waitFor(() => {
      expect(screen.getByText('商品管理')).toBeInTheDocument();
    });
  });

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

    (goodsClientManager.get().$get as any).mockResolvedValue(createMockResponse(200, mockGoods));

    renderWithProviders(<GoodsManagement />);

    // Test search
    const searchInput = screen.getByPlaceholderText('搜索商品名称...');
    fireEvent.change(searchInput, { target: { value: '搜索关键词' } });

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

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

  it('应该显示商品列表和分页信息', async () => {
    const mockGoods = {
      data: [
        {
          id: 1,
          name: '商品1',
          price: 100.00,
          costPrice: 50.00,
          categoryId1: 1,
          categoryId2: 2,
          categoryId3: 3,
          goodsType: 1,
          supplierId: 1,
          merchantId: 1,
          imageFileId: 1,
          slideImageIds: [],
          detail: '',
          instructions: '',
          sort: 0,
          state: 1,
          stock: 100,
          lowestBuy: 1,
          salesNum: 10,
          createdAt: '2024-01-01T00:00:00Z',
          updatedAt: '2024-01-01T00:00:00Z',
          createdBy: 1,
          updatedBy: 1,
          category1: { id: 1, name: '分类1' },
          category2: { id: 2, name: '分类2' },
          category3: { id: 3, name: '分类3' },
          supplier: { id: 1, name: '供应商1' },
          merchant: { id: 1, name: '商户1', username: 'merchant1' },
          imageFile: { id: 1, fullUrl: 'http://example.com/image.jpg' },
          slideImages: [],
        },
      ],
      pagination: {
        total: 25,
        page: 1,
        pageSize: 10,
      },
    };

    (goodsClientManager.get().$get as any).mockResolvedValue(createMockResponse(200, mockGoods));

    renderWithProviders(<GoodsManagement />);

    // Wait for data to load
    await waitFor(() => {
      expect(screen.getByText('商品1')).toBeInTheDocument();
    });

    // Verify pagination info
    expect(screen.getByText('共 25 条记录，第 1 / 3 页')).toBeInTheDocument();

    // Verify table columns
    expect(screen.getByText('商品图片')).toBeInTheDocument();
    expect(screen.getByText('商品名称')).toBeInTheDocument();
    expect(screen.getByText('价格')).toBeInTheDocument();
    expect(screen.getByText('库存')).toBeInTheDocument();
    expect(screen.getByText('销量')).toBeInTheDocument();
    expect(screen.getByText('供应商')).toBeInTheDocument();
    expect(screen.getByText('商户')).toBeInTheDocument();
    expect(screen.getByText('状态')).toBeInTheDocument();
    expect(screen.getByText('创建时间')).toBeInTheDocument();
  });
});