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

// 完整的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/supplierClient', () => {
  const mockSupplierClient = {
    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 mockSupplierClientManager = {
    get: vi.fn(() => mockSupplierClient),
  };

  return {
    supplierClientManager: mockSupplierClientManager,
    supplierClient: mockSupplierClient,
  };
});

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

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 user = userEvent.setup();
    const mockSuppliers = {
      data: [
        {
          id: 1,
          name: '测试供应商',
          username: 'testsupplier',
          realname: '张经理',
          phone: '13800138000',
          state: 1,
          createdAt: '2024-01-01T00:00:00Z',
        },
      ],
      pagination: {
        total: 1,
        page: 1,
        pageSize: 10,
      },
    };

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

    // Mock initial supplier list
    (supplierClient.index.$get as any).mockResolvedValue(createMockResponse(200, mockSuppliers));

    renderWithProviders(<SupplierManagement />);

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

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

    // Wait for dialog to open
    await waitFor(() => {
      expect(screen.getByTestId('create-supplier-submit-button')).toBeInTheDocument();
    });


    // Fill create form using placeholder text with fireEvent.change
    const nameInput = screen.getByPlaceholderText('请输入供应商名称');
    const usernameInput = screen.getByPlaceholderText('请输入用户名');
    const passwordInput = screen.getByPlaceholderText('请输入密码');
    const phoneInput = screen.getByPlaceholderText('请输入手机号码');

    fireEvent.change(nameInput, { target: { value: '新供应商' } });
    fireEvent.change(usernameInput, { target: { value: 'newsupplier' } });
    fireEvent.change(passwordInput, { target: { value: 'password123' } });
    fireEvent.change(phoneInput, { target: { value: '13800138000' } });

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

    const submitButton = screen.getByTestId('create-supplier-submit-button');

    await user.click(submitButton);

    await waitFor(() => {
      expect(supplierClient.index.$post).toHaveBeenCalledWith({
        json: {
          name: '新供应商',
          username: 'newsupplier',
          password: 'password123',
          phone: '13800138000',
          realname: '',
          state: 2,
        },
      });
      expect(toast.success).toHaveBeenCalledWith('创建成功');
    });

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

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

    // Update supplier
    const updateNameInput = screen.getByDisplayValue('测试供应商');
    fireEvent.change(updateNameInput, { target: { value: '更新供应商' } });

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

    const updateButton = screen.getByTestId('update-supplier-submit-button');
    await user.click(updateButton);

    await waitFor(() => {
      expect(supplierClient[':id']['$put']).toHaveBeenCalledWith({
        param: { id: 1 },
        json: {
          name: '更新供应商',
          username: 'testsupplier',
          phone: '13800138000',
          realname: '张经理',
          password: undefined,
          state: 1,
        },
      });
      expect(toast.success).toHaveBeenCalledWith('更新成功');
    });

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

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

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

    const confirmDeleteButton = screen.getByTestId('confirm-delete-button');
    await user.click(confirmDeleteButton);

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

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

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

    renderWithProviders(<SupplierManagement />);

    // Should handle error without crashing
    await waitFor(() => {
      expect(screen.getByText('供应商管理')).toBeInTheDocument();
    });

    // Test create supplier error
    const createButton = screen.getByText('创建供应商');
    fireEvent.click(createButton);

    const nameInput = screen.getByPlaceholderText('请输入供应商名称');
    const usernameInput = screen.getByPlaceholderText('请输入用户名');
    const passwordInput = screen.getByPlaceholderText('请输入密码');
    const phoneInput = screen.getByPlaceholderText('请输入手机号码');

    fireEvent.change(nameInput, { target: { value: '测试供应商' } });
    fireEvent.change(usernameInput, { target: { value: 'testsupplier' } });
    fireEvent.change(passwordInput, { target: { value: 'password' } });
    fireEvent.change(phoneInput, { target: { value: '13800138000' } });

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

    const submitButton = screen.getByTestId('create-supplier-submit-button');
    await user.click(submitButton);

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

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

    (supplierClient.index.$get as any).mockResolvedValue(createMockResponse(200, mockSuppliers));

    renderWithProviders(<SupplierManagement />);

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

    const searchButton = screen.getByTestId('search-button');
    fireEvent.click(searchButton);

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

  it('应该显示供应商状态', async () => {
    const mockSuppliers = {
      data: [
        {
          id: 1,
          name: '启用供应商',
          username: 'enabledsupplier',
          realname: '李经理',
          phone: '13900139000',
          state: 1,
          createdAt: '2024-01-01T00:00:00Z',
        },
        {
          id: 2,
          name: '禁用供应商',
          username: 'disabledsupplier',
          realname: '王经理',
          phone: '13700137000',
          state: 2,
          createdAt: '2024-01-02T00:00:00Z',
        },
      ],
      pagination: {
        total: 2,
        page: 1,
        pageSize: 10,
      },
    };

    (supplierClient.index.$get as any).mockResolvedValue(createMockResponse(200, mockSuppliers));

    renderWithProviders(<SupplierManagement />);

    await waitFor(() => {
      expect(screen.getByText('启用')).toBeInTheDocument();
      expect(screen.getByText('禁用')).toBeInTheDocument();
    });
  });
});