import React from 'react'
import { render, screen, fireEvent, waitFor } from '@testing-library/react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import HomePage from '../../src/pages/home/index'

// Mock Taro 导航
jest.mock('@tarojs/taro', () => ({
  navigateTo: jest.fn()
}))

// Mock AreaPicker 组件
jest.mock('../../src/components/AreaPicker', () => ({
  AreaPicker: jest.fn(({ visible, onClose, onConfirm, value, title }) => {
    if (!visible) return null

    return (
      <div data-testid="area-picker">
        <div data-testid="area-picker-title">{title}</div>
        <button data-testid="area-picker-confirm" onClick={() => onConfirm([1, 11, 101], [
          { id: 1, name: '北京市', type: 'province' },
          { id: 11, name: '北京市', type: 'city' },
          { id: 101, name: '朝阳区', type: 'district' }
        ])}>确认</button>
        <button data-testid="area-picker-cancel" onClick={onClose}>取消</button>
      </div>
    )
  })
}))

// Mock TabBarLayout 组件
jest.mock('@/layouts/tab-bar-layout', () => ({
  TabBarLayout: jest.fn(({ children, activeKey, className }) => (
    <div data-testid="tab-bar-layout" data-active-key={activeKey} className={className}>
      {children}
    </div>
  ))
}))

// 创建测试用的 QueryClient
const createTestQueryClient = () => new QueryClient({
  defaultOptions: {
    queries: {
      retry: false,
    },
  },
})

// 包装组件
const Wrapper = ({ children }: { children: React.ReactNode }) => {
  const queryClient = createTestQueryClient()
  return (
    <QueryClientProvider client={queryClient}>
      {children}
    </QueryClientProvider>
  )
}

describe('首页集成测试', () => {
  beforeEach(() => {
    jest.clearAllMocks()
  })

  test('应该正确渲染首页', () => {
    render(
      <Wrapper>
        <HomePage />
      </Wrapper>
    )

    // 检查轮播图
    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()
    expect(screen.getByText('选择日期')).toBeInTheDocument()

    // 检查查询按钮
    expect(screen.getByText('查询路线')).toBeInTheDocument()

    // 检查MVP限制说明
    expect(screen.getByText('更多功能正在开发中...')).toBeInTheDocument()
  })

  test('应该处理出行方式选择', () => {
    render(
      <Wrapper>
        <HomePage />
      </Wrapper>
    )

    // 默认选择大巴拼车
    const busOption = screen.getByText('大巴拼车')
    expect(busOption.parentElement).toHaveClass('bg-blue-500')

    // 选择商务车
    const businessOption = screen.getByText('商务车')
    fireEvent.click(businessOption)

    // 检查商务车被选中
    expect(businessOption.parentElement).toHaveClass('bg-blue-500')
    expect(busOption.parentElement).not.toHaveClass('bg-blue-500')
  })

  test('应该打开出发地选择器', () => {
    render(
      <Wrapper>
        <HomePage />
      </Wrapper>
    )

    // 初始状态下地区选择器应该隐藏
    expect(screen.queryByTestId('area-picker')).not.toBeInTheDocument()

    // 点击出发地选择按钮
    const startLocationButton = screen.getByText('出发地').closest('button')
    fireEvent.click(startLocationButton!)

    // 检查地区选择器显示
    expect(screen.getByTestId('area-picker')).toBeInTheDocument()
    expect(screen.getByTestId('area-picker-title')).toHaveTextContent('选择出发地')
  })

  test('应该打开目的地选择器', () => {
    render(
      <Wrapper>
        <HomePage />
      </Wrapper>
    )

    // 点击目的地选择按钮
    const endLocationButton = screen.getByText('目的地').closest('button')
    fireEvent.click(endLocationButton!)

    // 检查地区选择器显示
    expect(screen.getByTestId('area-picker')).toBeInTheDocument()
    expect(screen.getByTestId('area-picker-title')).toHaveTextContent('选择目的地')
  })

  test('应该处理地区选择确认', async () => {
    render(
      <Wrapper>
        <HomePage />
      </Wrapper>
    )

    // 打开出发地选择器
    const startLocationButton = screen.getByText('出发地').closest('button')
    fireEvent.click(startLocationButton!)

    // 确认选择
    const confirmButton = screen.getByTestId('area-picker-confirm')
    fireEvent.click(confirmButton)

    // 检查地区选择器关闭
    await waitFor(() => {
      expect(screen.queryByTestId('area-picker')).not.toBeInTheDocument()
    })

    // 检查出发地显示更新
    expect(screen.getByText('北京市 北京市 朝阳区')).toBeInTheDocument()
  })

  test('应该处理地区选择取消', async () => {
    render(
      <Wrapper>
        <HomePage />
      </Wrapper>
    )

    // 打开出发地选择器
    const startLocationButton = screen.getByText('出发地').closest('button')
    fireEvent.click(startLocationButton!)

    // 取消选择
    const cancelButton = screen.getByTestId('area-picker-cancel')
    fireEvent.click(cancelButton)

    // 检查地区选择器关闭
    await waitFor(() => {
      expect(screen.queryByTestId('area-picker')).not.toBeInTheDocument()
    })

    // 检查出发地显示未更新
    expect(screen.getByText('请选择地区')).toBeInTheDocument()
  })

  test('应该处理日期选择', () => {
    render(
      <Wrapper>
        <HomePage />
      </Wrapper>
    )

    // 获取日期显示文本
    const dateDisplay = screen.getByText('今天')
    expect(dateDisplay).toBeInTheDocument()

    // 检查日期选择器存在
    const datePicker = screen.getByText('选择日期')
    expect(datePicker).toBeInTheDocument()
  })

  test('应该处理出发地和目的地交换', () => {
    render(
      <Wrapper>
        <HomePage />
      </Wrapper>
    )

    // 先设置出发地和目的地
    // 打开出发地选择器并选择
    const startLocationButton = screen.getByText('出发地').closest('button')
    fireEvent.click(startLocationButton!)
    const confirmButton = screen.getByTestId('area-picker-confirm')
    fireEvent.click(confirmButton)

    // 打开目的地选择器并选择
    const endLocationButton = screen.getByText('目的地').closest('button')
    fireEvent.click(endLocationButton!)
    fireEvent.click(confirmButton)

    // 检查初始状态
    expect(screen.getAllByText('北京市 北京市 朝阳区')).toHaveLength(2)

    // 点击交换按钮
    const swapButton = screen.getByText('⇄').closest('button')
    fireEvent.click(swapButton!)

    // 检查出发地和目的地已交换
    // 注意：由于状态更新，可能需要等待重新渲染
  })

  test('应该验证查询条件', () => {
    const { navigateTo } = require('@tarojs/taro')

    render(
      <Wrapper>
        <HomePage />
      </Wrapper>
    )

    // 在没有选择出发地和目的地的情况下点击查询
    const searchButton = screen.getByText('查询路线')
    fireEvent.click(searchButton)

    // 检查没有进行导航
    expect(navigateTo).not.toHaveBeenCalled()
  })

  test('应该执行路线查询', async () => {
    const { navigateTo } = require('@tarojs/taro')

    render(
      <Wrapper>
        <HomePage />
      </Wrapper>
    )

    // 设置出发地
    const startLocationButton = screen.getByText('出发地').closest('button')
    fireEvent.click(startLocationButton!)
    const confirmButton = screen.getByTestId('area-picker-confirm')
    fireEvent.click(confirmButton)

    // 设置目的地
    const endLocationButton = screen.getByText('目的地').closest('button')
    fireEvent.click(endLocationButton!)
    fireEvent.click(confirmButton)

    // 等待状态更新
    await waitFor(() => {
      expect(screen.getAllByText('北京市 北京市 朝阳区')).toHaveLength(2)
    })

    // 点击查询按钮
    const searchButton = screen.getByText('查询路线')
    fireEvent.click(searchButton)

    // 检查导航被调用
    expect(navigateTo).toHaveBeenCalledWith({
      url: expect.stringContaining('pages/select-activity/ActivitySelectPage')
    })
  })

  test('应该正确格式化导航参数', async () => {
    const { navigateTo } = require('@tarojs/taro')

    render(
      <Wrapper>
        <HomePage />
      </Wrapper>
    )

    // 设置出发地
    const startLocationButton = screen.getByText('出发地').closest('button')
    fireEvent.click(startLocationButton!)
    const confirmButton = screen.getByTestId('area-picker-confirm')
    fireEvent.click(confirmButton)

    // 设置目的地
    const endLocationButton = screen.getByText('目的地').closest('button')
    fireEvent.click(endLocationButton!)
    fireEvent.click(confirmButton)

    // 等待状态更新
    await waitFor(() => {
      expect(screen.getAllByText('北京市 北京市 朝阳区')).toHaveLength(2)
    })

    // 点击查询按钮
    const searchButton = screen.getByText('查询路线')
    fireEvent.click(searchButton)

    // 检查导航参数格式
    const navigateCall = navigateTo.mock.calls[0][0]
    expect(navigateCall.url).toContain('startAreaIds=[1,11,101]')
    expect(navigateCall.url).toContain('endAreaIds=[1,11,101]')
    expect(navigateCall.url).toContain('date=')
    expect(navigateCall.url).toContain('vehicleType=bus')
  })

  test('应该显示正确的布局', () => {
    render(
      <Wrapper>
        <HomePage />
      </Wrapper>
    )

    // 检查TabBarLayout是否正确使用
    const tabBarLayout = screen.getByTestId('tab-bar-layout')
    expect(tabBarLayout).toHaveAttribute('data-active-key', 'home')
    expect(tabBarLayout).toHaveClass('bg-gradient-to-b from-blue-500 to-blue-600')
  })

  test('应该处理默认日期显示', () => {
    render(
      <Wrapper>
        <HomePage />
      </Wrapper>
    )

    // 检查默认日期显示为今天
    const dateDisplay = screen.getByText('今天')
    expect(dateDisplay).toBeInTheDocument()
  })

  test('应该处理默认出行方式', () => {
    render(
      <Wrapper>
        <HomePage />
      </Wrapper>
    )

    // 检查默认选择大巴拼车
    const busOption = screen.getByText('大巴拼车')
    expect(busOption.parentElement).toHaveClass('bg-blue-500')
  })
})