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

// Mock Taro
jest.mock('@tarojs/taro', () => ({
  showToast: jest.fn(),
  showModal: jest.fn(({ success }) => success?.({ confirm: true })),
  removeStorageSync: jest.fn(),
  reLaunch: jest.fn()
}))

// Mock auth hook
jest.mock('@d8d/mini-enterprise-auth-ui/hooks', () => ({
  useAuth: jest.fn(() => ({
    user: {
      id: 1,
      username: 'testuser',
      nickname: '测试企业',
      company: {
        id: 1,
        companyName: '阿里巴巴集团',
        contactPerson: '张三',
        contactPhone: '13800138000',
        status: 1,
        createTime: '2023-01-01',
        updateTime: '2023-01-01'
      }
    },
    logout: jest.fn()
  }))
}))

// Mock API client
jest.mock('../src/api/companyClient', () => ({
  enterpriseCompanyClient: {
    overview: {
      $get: jest.fn()
    }
  }
}))

// Mock layouts
jest.mock('@d8d/yongren-shared-ui/components/YongrenTabBarLayout', () => ({
  YongrenTabBarLayout: ({ children, activeKey }: any) => (
    <div data-testid="tab-bar-layout" data-active-key={activeKey}>
      {children}
    </div>
  )
}))

jest.mock('@d8d/mini-shared-ui-components/components/navbar', () => ({
  Navbar: ({ title }: any) => <div data-testid="navbar">{title}</div>
}))

const { enterpriseCompanyClient } = require('../../api/companyClient')
const { useAuth } = require('@d8d/mini-enterprise-auth-ui/hooks')
const Taro = require('@tarojs/taro')

const createTestQueryClient = () => new QueryClient({
  defaultOptions: {
    queries: { retry: false },
    mutations: { retry: false }
  }
})

const renderWithQueryClient = (component: React.ReactElement) => {
  const queryClient = createTestQueryClient()
  return render(
    <QueryClientProvider client={queryClient}>
      {component}
    </QueryClientProvider>
  )
}

describe('Settings', () => {
  beforeEach(() => {
    jest.clearAllMocks()
  })

  describe('企业信息展示', () => {
    it('应该显示加载状态', () => {
      enterpriseCompanyClient.overview.$get.mockImplementation(
        () => new Promise(() => {})
      )

      renderWithQueryClient(<Settings />)

      expect(screen.getByText('加载中...')).toBeInTheDocument()
    })

    it('应该成功加载并显示企业信息', async () => {
      const mockOverview = {
        '在职人员数': 24,
        '进行中订单数': 3,
        '已完成订单数': 9,
        '累计订单数': 12
      }

      enterpriseCompanyClient.overview.$get.mockResolvedValue({
        ok: true,
        json: async () => mockOverview
      })

      renderWithQueryClient(<Settings />)

      await waitFor(() => {
        expect(screen.getByText('阿里巴巴集团')).toBeInTheDocument()
        expect(screen.getByText('24')).toBeInTheDocument()
        expect(screen.getByText('3')).toBeInTheDocument()
        expect(screen.getByText('12')).toBeInTheDocument()
        expect(screen.getByText('在职人员')).toBeInTheDocument()
        expect(screen.getByText('进行中订单')).toBeInTheDocument()
        expect(screen.getByText('累计订单')).toBeInTheDocument()
      })
    })

    it('应该显示企业账号标识', async () => {
      enterpriseCompanyClient.overview.$get.mockResolvedValue({
        ok: true,
        json: async () => ({})
      })

      renderWithQueryClient(<Settings />)

      await waitFor(() => {
        expect(screen.getByText('企业账号')).toBeInTheDocument()
      })
    })
  })

  describe('功能列表', () => {
    beforeEach(async () => {
      enterpriseCompanyClient.overview.$get.mockResolvedValue({
        ok: true,
        json: async () => ({})
      })
    })

    it('应该显示所有功能项', async () => {
      renderWithQueryClient(<Settings />)

      await waitFor(() => {
        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()
      })
    })

    it('应该显示延期功能的标识', async () => {
      renderWithQueryClient(<Settings />)

      await waitFor(() => {
        const deferredLabels = screen.getAllByText('（后期优化）')
        expect(deferredLabels.length).toBeGreaterThan(0)
      })
    })
  })

  describe('延期功能处理', () => {
    beforeEach(async () => {
      enterpriseCompanyClient.overview.$get.mockResolvedValue({
        ok: true,
        json: async () => ({})
      })
    })

    it('点击延期功能应该显示提示', async () => {
      renderWithQueryClient(<Settings />)

      await waitFor(() => {
        expect(screen.getByText('账号信息')).toBeInTheDocument()
      })

      fireEvent.click(screen.getByText('账号信息'))

      expect(Taro.showModal).toHaveBeenCalledWith(
        expect.objectContaining({
          title: '功能开发中',
          content: expect.stringContaining('账号信息功能正在开发中')
        })
      )
    })

    it('点击安全设置应该显示提示', async () => {
      renderWithQueryClient(<Settings />)

      await waitFor(() => {
        expect(screen.getByText('安全设置')).toBeInTheDocument()
      })

      fireEvent.click(screen.getByText('安全设置'))

      expect(Taro.showModal).toHaveBeenCalledWith(
        expect.objectContaining({
          title: '功能开发中',
          content: expect.stringContaining('安全设置功能正在开发中')
        })
      )
    })

    it('点击消息通知应该显示提示', async () => {
      renderWithQueryClient(<Settings />)

      await waitFor(() => {
        expect(screen.getByText('消息通知')).toBeInTheDocument()
      })

      fireEvent.click(screen.getByText('消息通知'))

      expect(Taro.showModal).toHaveBeenCalledWith(
        expect.objectContaining({
          title: '功能开发中',
          content: expect.stringContaining('消息通知功能正在开发中')
        })
      )
    })
  })

  describe('退出登录', () => {
    beforeEach(async () => {
      enterpriseCompanyClient.overview.$get.mockResolvedValue({
        ok: true,
        json: async () => ({})
      })
    })

    it('点击退出登录应该显示确认对话框', async () => {
      renderWithQueryClient(<Settings />)

      await waitFor(() => {
        expect(screen.getByText('退出登录')).toBeInTheDocument()
      })

      fireEvent.click(screen.getByText('退出登录'))

      expect(Taro.showModal).toHaveBeenCalledWith(
        expect.objectContaining({
          title: '退出登录',
          content: '确定要退出登录吗？'
        })
      )
    })

    it('确认退出登录应该清除认证信息并跳转', async () => {
      renderWithQueryClient(<Settings />)

      await waitFor(() => {
        expect(screen.getByText('退出登录')).toBeInTheDocument()
      })

      fireEvent.click(screen.getByText('退出登录'))

      await waitFor(() => {
        expect(Taro.removeStorageSync).toHaveBeenCalledWith('enterpriseToken')
        expect(Taro.removeStorageSync).toHaveBeenCalledWith('enterpriseUser')
        expect(Taro.reLaunch).toHaveBeenCalledWith({
          url: '/pages/login/index'
        })
      })
    })
  })

  describe('其他功能', () => {
    beforeEach(async () => {
      enterpriseCompanyClient.overview.$get.mockResolvedValue({
        ok: true,
        json: async () => ({})
      })
    })

    it('点击帮助中心应该显示提示', async () => {
      renderWithQueryClient(<Settings />)

      await waitFor(() => {
        expect(screen.getByText('帮助中心')).toBeInTheDocument()
      })

      fireEvent.click(screen.getByText('帮助中心'))

      expect(Taro.showToast).toHaveBeenCalledWith(
        expect.objectContaining({ title: '即将开放' })
      )
    })

    it('点击用户协议应该显示提示', async () => {
      renderWithQueryClient(<Settings />)

      await waitFor(() => {
        expect(screen.getByText('用户协议')).toBeInTheDocument()
      })

      fireEvent.click(screen.getByText('用户协议'))

      expect(Taro.showToast).toHaveBeenCalledWith(
        expect.objectContaining({ title: '即将开放' })
      )
    })

    it('点击隐私政策应该显示提示', async () => {
      renderWithQueryClient(<Settings />)

      await waitFor(() => {
        expect(screen.getByText('隐私政策')).toBeInTheDocument()
      })

      fireEvent.click(screen.getByText('隐私政策'))

      expect(Taro.showToast).toHaveBeenCalledWith(
        expect.objectContaining({ title: '即将开放' })
      )
    })
  })

  describe('组件集成', () => {
    it('应该正确集成Navbar组件', async () => {
      enterpriseCompanyClient.overview.$get.mockResolvedValue({
        ok: true,
        json: async () => ({})
      })

      renderWithQueryClient(<Settings />)

      await waitFor(() => {
        const navbar = screen.getByTestId('navbar')
        expect(navbar).toBeInTheDocument()
        expect(navbar).toHaveTextContent('企业设置')
      })
    })

    it('应该正确集成TabBarLayout并激活settings标签', async () => {
      enterpriseCompanyClient.overview.$get.mockResolvedValue({
        ok: true,
        json: async () => ({})
      })

      renderWithQueryClient(<Settings />)

      await waitFor(() => {
        const layout = screen.getByTestId('tab-bar-layout')
        expect(layout).toHaveAttribute('data-active-key', 'settings')
      })
    })

    it('应该正确集成useAuth hook', async () => {
      enterpriseCompanyClient.overview.$get.mockResolvedValue({
        ok: true,
        json: async () => ({})
      })

      renderWithQueryClient(<Settings />)

      await waitFor(() => {
        expect(useAuth).toHaveBeenCalled()
        expect(screen.getByText('阿里巴巴集团')).toBeInTheDocument()
      })
    })
  })
})
