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

// Mock disabilityClient
vi.mock('../../src/api/disabilityClient', () => ({
  disabilityClientManager: {
    get: vi.fn(() => ({
      findPersonsWithCompany: {
        $get: vi.fn(() => Promise.resolve({
          status: 200,
          json: async () => ({
            data: [
              {
                personId: 1,
                orderId: 1,
                name: '张三',
                disabilityType: '肢体残疾',
                disabilityLevel: '二级',
                companyName: '测试公司A',
                disabilityId: '110101199001011234',
                city: '北京市',
                district: '朝阳区'
              },
              {
                personId: 2,
                orderId: 2,
                name: '李四',
                disabilityType: '视力残疾',
                disabilityLevel: '一级',
                companyName: null,
                disabilityId: '110101199002022345',
                city: '北京市',
                district: '海淀区'
              }
            ],
            total: 2
          })
        }))
      }
    }))
  }
}));

// Mock DataTablePagination
vi.mock('@d8d/shared-ui-components/components/admin/DataTablePagination', () => ({
  DataTablePagination: function DataTablePaginationMock(props: any) {
    const { currentPage, pageSize, totalCount, onPageChange } = props;
    return React.createElement('div', { 'data-testid': 'pagination' },
      React.createElement('span', null, `Page: ${currentPage}`),
      React.createElement('span', null, `PageSize: ${pageSize}`),
      React.createElement('span', null, `Total: ${totalCount}`),
      React.createElement('button', { onClick: () => onPageChange(2, 10) }, 'Next')
    );
  }
}));

// Test wrapper component
const TestWrapper: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const queryClient = new QueryClient({
    defaultOptions: {
      queries: {
        retry: false,
      },
    },
  });

  return (
    <QueryClientProvider client={queryClient}>
      {children}
    </QueryClientProvider>
  );
};

describe('DisabilityPersonCompanyQuery', () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it('应该正确渲染组件', () => {
    render(
      <TestWrapper>
        <DisabilityPersonCompanyQuery />
      </TestWrapper>
    );

    expect(screen.getByText('残疾人企业查询')).toBeInTheDocument();
    expect(screen.getByTestId('gender-filter')).toBeInTheDocument();
    expect(screen.getByTestId('disability-type-filter')).toBeInTheDocument();
    expect(screen.getByTestId('disability-level-filter')).toBeInTheDocument();
    expect(screen.getByTestId('min-age-filter')).toBeInTheDocument();
    expect(screen.getByTestId('max-age-filter')).toBeInTheDocument();
    expect(screen.getByTestId('company-name-filter')).toBeInTheDocument();
    expect(screen.getByTestId('city-filter')).toBeInTheDocument();
    expect(screen.getByTestId('district-filter')).toBeInTheDocument();
    expect(screen.getByTestId('disability-id-filter')).toBeInTheDocument();
  });

  it('应该显示所有筛选条件的输入框', () => {
    render(
      <TestWrapper>
        <DisabilityPersonCompanyQuery />
      </TestWrapper>
    );

    // 使用 getAllByText 因为这些文本可能在多个地方出现（筛选条件和表格标题）
    expect(screen.getAllByText('性别').length).toBeGreaterThan(0);
    expect(screen.getAllByText('残疾类别').length).toBeGreaterThan(0);
    expect(screen.getAllByText('残疾等级').length).toBeGreaterThan(0);
    expect(screen.getAllByText('最小年龄').length).toBeGreaterThan(0);
    expect(screen.getAllByText('最大年龄').length).toBeGreaterThan(0);
    expect(screen.getAllByText('公司名称').length).toBeGreaterThan(0);
    expect(screen.getAllByText('市').length).toBeGreaterThan(0);
    expect(screen.getAllByText('区').length).toBeGreaterThan(0);
    expect(screen.getAllByText('残疾证号').length).toBeGreaterThan(0);
  });

  it('应该正确显示公司名称筛选的 placeholder', () => {
    render(
      <TestWrapper>
        <DisabilityPersonCompanyQuery />
      </TestWrapper>
    );

    const companyNameFilter = screen.getByTestId('company-name-filter');
    expect(companyNameFilter).toHaveAttribute('placeholder', '输入公司名称进行筛选');
  });

  it('应该正确显示市筛选的 placeholder', () => {
    render(
      <TestWrapper>
        <DisabilityPersonCompanyQuery />
      </TestWrapper>
    );

    const cityFilter = screen.getByTestId('city-filter');
    expect(cityFilter).toHaveAttribute('placeholder', '例如：广州市');
  });

  it('应该正确显示区筛选的 placeholder', () => {
    render(
      <TestWrapper>
        <DisabilityPersonCompanyQuery />
      </TestWrapper>
    );

    const districtFilter = screen.getByTestId('district-filter');
    expect(districtFilter).toHaveAttribute('placeholder', '例如：天河区');
  });

  it('应该正确显示残疾证号筛选的 placeholder', () => {
    render(
      <TestWrapper>
        <DisabilityPersonCompanyQuery />
      </TestWrapper>
    );

    const disabilityIdFilter = screen.getByTestId('disability-id-filter');
    expect(disabilityIdFilter).toHaveAttribute('placeholder', '输入完整的残疾证号');
  });

  it('应该有重置和查询按钮', () => {
    render(
      <TestWrapper>
        <DisabilityPersonCompanyQuery />
      </TestWrapper>
    );

    expect(screen.getByTestId('reset-button')).toBeInTheDocument();
    expect(screen.getByTestId('search-button')).toBeInTheDocument();
    expect(screen.getByText('重置')).toBeInTheDocument();
    expect(screen.getByText('查询')).toBeInTheDocument();
  });

  it('应该有占位符操作按钮（新增、编辑、删除）', () => {
    render(
      <TestWrapper>
        <DisabilityPersonCompanyQuery />
      </TestWrapper>
    );

    const addButton = screen.getByText('新增');
    const editButton = screen.getByText('编辑');
    const deleteButton = screen.getByText('删除');

    expect(addButton).toBeInTheDocument();
    expect(addButton).toBeDisabled();
    expect(addButton).toHaveAttribute('title', '此功能待实现：打开对话框创建新的残疾人企业关联');

    expect(editButton).toBeInTheDocument();
    expect(editButton).toBeDisabled();
    expect(editButton).toHaveAttribute('title', '此功能待实现：选中一条记录后打开对话框修改关联信息');

    expect(deleteButton).toBeInTheDocument();
    expect(deleteButton).toBeDisabled();
    expect(deleteButton).toHaveAttribute('title', '此功能待实现：选中一条记录后确认并删除关联');
  });

  it('应该有导出按钮', () => {
    render(
      <TestWrapper>
        <DisabilityPersonCompanyQuery />
      </TestWrapper>
    );

    const exportButton = screen.getByTestId('export-button');
    expect(exportButton).toBeInTheDocument();
    expect(exportButton).toHaveTextContent('导出数据');
    expect(exportButton).toHaveAttribute('title', '导出当前筛选结果为CSV文件');
  });

  it('应该能够输入公司名称筛选', () => {
    render(
      <TestWrapper>
        <DisabilityPersonCompanyQuery />
      </TestWrapper>
    );

    const companyNameInput = screen.getByTestId('company-name-filter');
    fireEvent.change(companyNameInput, { target: { value: '测试公司' } });

    expect(companyNameInput).toHaveValue('测试公司');
  });

  it('应该能够输入市级筛选', () => {
    render(
      <TestWrapper>
        <DisabilityPersonCompanyQuery />
      </TestWrapper>
    );

    const cityInput = screen.getByTestId('city-filter');
    fireEvent.change(cityInput, { target: { value: '北京市' } });

    expect(cityInput).toHaveValue('北京市');
  });

  it('应该能够输入区级筛选', () => {
    render(
      <TestWrapper>
        <DisabilityPersonCompanyQuery />
      </TestWrapper>
    );

    const districtInput = screen.getByTestId('district-filter');
    fireEvent.change(districtInput, { target: { value: '朝阳区' } });

    expect(districtInput).toHaveValue('朝阳区');
  });

  it('应该能够输入残疾证号筛选', () => {
    render(
      <TestWrapper>
        <DisabilityPersonCompanyQuery />
      </TestWrapper>
    );

    const disabilityIdInput = screen.getByTestId('disability-id-filter');
    fireEvent.change(disabilityIdInput, { target: { value: '110101199001011234' } });

    expect(disabilityIdInput).toHaveValue('110101199001011234');
  });

  it('应该能够输入最小和最大年龄筛选', () => {
    render(
      <TestWrapper>
        <DisabilityPersonCompanyQuery />
      </TestWrapper>
    );

    const minAgeInput = screen.getByTestId('min-age-filter');
    const maxAgeInput = screen.getByTestId('max-age-filter');

    fireEvent.change(minAgeInput, { target: { value: '18' } });
    fireEvent.change(maxAgeInput, { target: { value: '60' } });

    // Input type="number" 的 value 会转换为 number 类型
    expect(minAgeInput).toHaveValue(18);
    expect(maxAgeInput).toHaveValue(60);
  });

  it('表格不应该有"户籍"列', () => {
    render(
      <TestWrapper>
        <DisabilityPersonCompanyQuery />
      </TestWrapper>
    );

    const table = screen.getByTestId('results-table');
    const headers = within(table).getAllByRole('columnheader');

    expect(headers.some(h => h.textContent === '户籍')).toBe(false);

    expect(headers.some(h => h.textContent === '姓名')).toBe(true);
    expect(headers.some(h => h.textContent === '残疾类别')).toBe(true);
    expect(headers.some(h => h.textContent === '残疾等级')).toBe(true);
    expect(headers.some(h => h.textContent === '公司')).toBe(true);
    expect(headers.some(h => h.textContent === '残疾证号')).toBe(true);
    expect(headers.some(h => h.textContent === '区')).toBe(true);
    expect(headers.some(h => h.textContent === '市')).toBe(true);
  });
});
