import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import '@testing-library/jest-dom';
import { LoginPage } from '@/client/admin/pages/Login';
import { TestWrapper } from '~/utils/client/test-render';

// Mock useAuth钩子
const mockLogin = vi.fn();
const mockNavigate = vi.fn();

vi.mock('@/client/admin/hooks/AuthProvider', () => ({
  useAuth: () => ({
    login: mockLogin,
    user: null,
    token: null,
    isAuthenticated: false,
    isLoading: false,
    logout: vi.fn(),
  }),
}));

vi.mock('react-router', () => ({
  useNavigate: () => mockNavigate,
}));

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

describe('LoginPage 集成测试', () => {
  const user = userEvent.setup();

  beforeEach(() => {
    vi.clearAllMocks();
  });

  it('应该正确渲染登录页面标题和品牌元素', async () => {
    render(<LoginPage />, { wrapper: TestWrapper });

    expect(screen.getByText('管理后台登录')).toBeInTheDocument();
    expect(screen.getByText('请输入您的账号和密码继续操作')).toBeInTheDocument();
    expect(screen.getByText('欢迎登录')).toBeInTheDocument();
  });

  it('应该包含用户名和密码输入字段', async () => {
    render(<LoginPage />, { wrapper: TestWrapper });

    expect(screen.getByPlaceholderText('请输入用户名')).toBeInTheDocument();
    expect(screen.getByPlaceholderText('请输入密码')).toBeInTheDocument();
  });

  it('应该显示密码可见性切换按钮', async () => {
    render(<LoginPage />, { wrapper: TestWrapper });

    const passwordInput = screen.getByPlaceholderText('请输入密码');
    expect(passwordInput).toHaveAttribute('type', 'password');

    // 查找密码可见性切换按钮
    const toggleButtons = screen.getAllByRole('button');
    const toggleButton = toggleButtons.find(button =>
      button.querySelector('svg[class*="eye"]')
    );

    expect(toggleButton).toBeDefined();
    if (toggleButton) {
      await user.click(toggleButton);
      expect(passwordInput).toHaveAttribute('type', 'text');
    }
  });

  it('应该验证表单必填字段', async () => {
    render(<LoginPage />, { wrapper: TestWrapper });

    const submitButton = screen.getByRole('button', { name: '登录' });
    await user.click(submitButton);

    // 验证错误消息显示
    expect(screen.getByText('请输入用户名')).toBeInTheDocument();
    expect(screen.getByText('请输入密码')).toBeInTheDocument();
  });

  it('应该显示加载状态当表单提交时', async () => {
    // 使用ref来安全地存储resolve函数
    const resolveRef = { current: undefined as ((value?: unknown) => void) | undefined };

    mockLogin.mockImplementation(() => new Promise((resolve) => {
      resolveRef.current = resolve;
    }));

    render(<LoginPage />, { wrapper: TestWrapper });

    // 填写表单
    await user.type(screen.getByPlaceholderText('请输入用户名'), 'testuser');
    await user.type(screen.getByPlaceholderText('请输入密码'), 'testpassword');

    const submitButton = screen.getByRole('button', { name: '登录' });
    await user.click(submitButton);

    // 验证按钮状态变为禁用（表示加载中）
    await waitFor(() => {
      expect(submitButton).toBeDisabled();
    });

    // 清理 - 安全地调用resolve函数
    if (resolveRef.current) {
      resolveRef.current();
    }
  });

  it('应该显示测试账号信息', async () => {
    render(<LoginPage />, { wrapper: TestWrapper });

    // 使用更灵活的文本匹配器，因为文本被多个元素分割
    expect(screen.getByText(/测试账号:/)).toBeInTheDocument();
    expect(screen.getByText('admin')).toBeInTheDocument();
    expect(screen.getByText('admin123')).toBeInTheDocument();
  });

  it('应该包含版权信息和联系链接', async () => {
    render(<LoginPage />, { wrapper: TestWrapper });

    const currentYear = new Date().getFullYear();
    expect(screen.getByText(`© ${currentYear} 管理系统. 保留所有权利.`)).toBeInTheDocument();
    expect(screen.getByText('遇到问题？')).toBeInTheDocument();
    expect(screen.getByText('联系管理员')).toBeInTheDocument();
  });

  it('应该具有正确的样式类名', async () => {
    const { container } = render(<LoginPage />, { wrapper: TestWrapper });

    // 验证背景渐变
    const bgGradient = container.querySelector('.bg-gradient-to-br');
    expect(bgGradient).not.toBeNull();

    // 验证卡片阴影
    const shadowCard = container.querySelector('.shadow-xl');
    expect(shadowCard).not.toBeNull();

    // 验证响应式 padding - 分开查询每个断点
    const hasPx4 = container.querySelector('.px-4');
    const hasSmPx6 = container.querySelector('[class*="sm:px-6"]');
    const hasLgPx8 = container.querySelector('[class*="lg:px-8"]');
    expect(hasPx4).not.toBeNull();
    expect(hasSmPx6).not.toBeNull();
    expect(hasLgPx8).not.toBeNull();
  });

  it('应该包含正确的图标', async () => {
    render(<LoginPage />, { wrapper: TestWrapper });

    // 验证用户图标存在（通过类名查找）
    const userIcons = document.querySelectorAll('.lucide-user');
    expect(userIcons.length).toBeGreaterThan(0);

    // 验证锁图标存在（通过类名查找）
    const lockIcons = document.querySelectorAll('.lucide-lock');
    expect(lockIcons.length).toBeGreaterThan(0);

    // 验证眼睛图标存在（用于密码可见性切换）
    const eyeIcons = document.querySelectorAll('.lucide-eye, .lucide-eye-off');
    expect(eyeIcons.length).toBeGreaterThan(0);
  });
});