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 { BankNameSelector } from '../../src/components/BankNameSelector'
import { bankNameClient } from '../../src/api/bankNameClient'

// Mock the bank name client
vi.mock('../../src/api/bankNameClient', () => {
  const bankNameClient = {
    index: {
      $get: vi.fn(),
    },
  }
  return {
    bankNameClient,
    bankNameClientManager: {
      get: vi.fn(() => bankNameClient),
    },
  }
})

const mockBankNames = {
  data: [
    { id: 1, name: '中国工商银行', code: 'ICBC', status: 1, createdAt: '2024-01-01' },
    { id: 2, name: '中国建设银行', code: 'CCB', status: 1, createdAt: '2024-01-01' },
    { id: 3, name: '中国农业银行', code: 'ABC', status: 0, createdAt: '2024-01-01' },
  ],
  pagination: {
    total: 3,
    page: 1,
    pageSize: 10,
    totalPages: 1,
  },
}

const TestWrapper = ({ children }: { children: React.ReactNode }) => {
  const queryClient = new QueryClient({
    defaultOptions: {
      queries: {
        retry: false,
      },
    },
  })

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

describe('BankNameSelector 集成测试', () => {
  beforeEach(() => {
    vi.clearAllMocks()
  })

  it('应该正确渲染银行名称选择器', async () => {
    (bankNameClient.index.$get as any).mockResolvedValue({
      status: 200,
      json: async () => mockBankNames,
    })

    render(
      <TestWrapper>
        <BankNameSelector testId="bank-name-selector" />
      </TestWrapper>
    )

    // 验证加载状态
    expect(screen.getByTestId('bank-name-selector')).toBeInTheDocument()
    expect(screen.getByText('加载中...')).toBeInTheDocument()

    // 等待数据加载完成
    await waitFor(() => {
      expect(screen.getByText('请选择银行名称')).toBeInTheDocument()
    })

    // 点击选择器打开下拉菜单
    const selectTrigger = screen.getByTestId('bank-name-selector')
    fireEvent.click(selectTrigger)

    // 验证下拉菜单中的选项
    await waitFor(() => {
      expect(screen.getByText('中国工商银行')).toBeInTheDocument()
      expect(screen.getByText('中国建设银行')).toBeInTheDocument()
      expect(screen.getByText('中国农业银行')).toBeInTheDocument()
    })
  })

  it('应该处理加载状态', () => {
    // Mock 延迟响应
    (bankNameClient.index.$get as any).mockImplementation(
      () => new Promise(() => {}) // 永不解析的Promise
    )

    render(
      <TestWrapper>
        <BankNameSelector testId="bank-name-selector" />
      </TestWrapper>
    )

    // 验证加载状态
    expect(screen.getByTestId('bank-name-selector')).toBeInTheDocument()
    expect(screen.getByText('加载中...')).toBeInTheDocument()
  })

  it('应该处理错误状态', async () => {
    (bankNameClient.index.$get as any).mockRejectedValue(new Error('API错误'))

    render(
      <TestWrapper>
        <BankNameSelector testId="bank-name-selector" />
      </TestWrapper>
    )

    // 等待错误状态
    await waitFor(() => {
      expect(screen.getByText('加载银行名称失败')).toBeInTheDocument()
    })
  })

  it('应该处理选择器值变化', async () => {
    (bankNameClient.index.$get as any).mockResolvedValue({
      status: 200,
      json: async () => mockBankNames,
    })

    const mockOnChange = vi.fn()

    render(
      <TestWrapper>
        <BankNameSelector onChange={mockOnChange} testId="bank-name-selector" />
      </TestWrapper>
    )

    // 等待数据加载完成
    await waitFor(() => {
      expect(screen.getByTestId('bank-name-selector')).toBeEnabled()
    })

    // 点击选择器打开下拉菜单
    const selectTrigger = screen.getByTestId('bank-name-selector')
    fireEvent.click(selectTrigger)

    // 选择第一个选项
    await waitFor(() => {
      const firstOption = screen.getByText('中国工商银行')
      fireEvent.click(firstOption)
    })

    // 验证onChange被调用
    expect(mockOnChange).toHaveBeenCalledWith(1)
  })

  it('应该支持自定义占位符', async () => {
    (bankNameClient.index.$get as any).mockResolvedValue({
      status: 200,
      json: async () => mockBankNames,
    })

    render(
      <TestWrapper>
        <BankNameSelector placeholder="选择银行名称" testId="bank-name-selector" />
      </TestWrapper>
    )

    // 等待数据加载完成
    await waitFor(() => {
      expect(screen.getByText('选择银行名称')).toBeInTheDocument()
    })
  })

  it('应该支持禁用状态', async () => {
    (bankNameClient.index.$get as any).mockResolvedValue({
      status: 200,
      json: async () => mockBankNames,
    })

    render(
      <TestWrapper>
        <BankNameSelector disabled={true} testId="bank-name-selector" />
      </TestWrapper>
    )

    // 等待数据加载完成
    await waitFor(() => {
      const selectTrigger = screen.getByTestId('bank-name-selector')
      expect(selectTrigger).toBeDisabled()
    })
  })

  it('应该支持预选值', async () => {
    (bankNameClient.index.$get as any).mockResolvedValue({
      status: 200,
      json: async () => mockBankNames,
    })

    render(
      <TestWrapper>
        <BankNameSelector value={2} testId="bank-name-selector" />
      </TestWrapper>
    )

    // 等待数据加载完成
    await waitFor(() => {
      expect(screen.getByTestId('bank-name-selector')).toBeEnabled()
    })

    // 验证预选值已正确设置
    // 在Radix UI Select中，预选值会显示在选择器触发器中
    const selectTrigger = screen.getByTestId('bank-name-selector')
    expect(selectTrigger).toHaveTextContent('中国建设银行')
  })
})