import { describe, it, expect } from 'vitest';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { Button } from '../Button';

describe('Button Component', () => {
  describe('正常情况', () => {
    it('应该渲染按钮文本', () => {
      render(<Button>点击我</Button>);
      expect(screen.getByRole('button', { name: '点击我' })).toBeInTheDocument();
    });

    it('应该调用 onClick 回调', async () => {
      const handleClick = vi.fn();
      const user = userEvent.setup();

      render(<Button onClick={handleClick}>点击</Button>);
      await user.click(screen.getByRole('button'));

      expect(handleClick).toHaveBeenCalledTimes(1);
    });

    it('应该支持不同的变体样式', () => {
      const { rerender } = render(<Button variant="primary">主要按钮</Button>);
      expect(screen.getByRole('button')).toHaveClass('bg-blue-600');

      rerender(<Button variant="secondary">次要按钮</Button>);
      expect(screen.getByRole('button')).toHaveClass('bg-gray-200');

      rerender(<Button variant="danger">危险按钮</Button>);
      expect(screen.getByRole('button')).toHaveClass('bg-red-600');
    });

    it('应该支持不同的尺寸', () => {
      const { rerender } = render(<Button size="sm">小按钮</Button>);
      expect(screen.getByRole('button')).toHaveClass('text-sm', 'px-3', 'py-1');

      rerender(<Button size="md">中等按钮</Button>);
      expect(screen.getByRole('button')).toHaveClass('text-base', 'px-4', 'py-2');

      rerender(<Button size="lg">大按钮</Button>);
      expect(screen.getByRole('button')).toHaveClass('text-lg', 'px-6', 'py-3');
    });
  });

  describe('边界条件', () => {
    it('应该处理空文本', () => {
      render(<Button></Button>);
      expect(screen.getByRole('button')).toBeInTheDocument();
    });

    it('应该处理长文本', () => {
      const longText = '这是一个非常非常非常长的按钮文本';
      render(<Button>{longText}</Button>);
      expect(screen.getByRole('button')).toHaveTextContent(longText);
    });
  });

  describe('异常情况', () => {
    it('应该在禁用状态不响应点击', async () => {
      const handleClick = vi.fn();
      const user = userEvent.setup();

      render(
        <Button onClick={handleClick} disabled>
          禁用按钮
        </Button>
      );
      await user.click(screen.getByRole('button'));

      expect(handleClick).not.toHaveBeenCalled();
    });

    it('应该在加载状态显示加载指示器', () => {
      render(
        <Button loading>
          加载中
        </Button>
      );
      expect(screen.getByRole('button')).toBeDisabled();
      expect(screen.getByText(/加载/i)).toBeInTheDocument();
    });
  });

  describe('可访问性', () => {
    it('应该支持自定义 aria-label', () => {
      render(
        <Button aria-label="关闭对话框">
          <span aria-hidden="true">×</span>
        </Button>
      );
      expect(screen.getByRole('button')).toHaveAttribute('aria-label', '关闭对话框');
    });

    it('应该正确设置 disabled 属性', () => {
      render(<Button disabled>禁用</Button>);
      expect(screen.getByRole('button')).toBeDisabled();
    });
  });
});
