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 { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { ActivityForm } from '@/client/admin/components/ActivityForm';
import { ActivityType } from '@d8d/server/modules/activities/activity.entity';

// Mock API 客户端

// 创建测试包装器
const TestWrapper = ({ children }: { children: React.ReactNode }) => {
  const queryClient = new QueryClient({
    defaultOptions: {
      queries: {
        retry: false,
      },
    },
  });

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

// Mock API 客户端
vi.mock('@/client/api', () => ({
  locationClient: {
    $get: vi.fn().mockResolvedValue({
      status: 200,
      ok: true,
      json: async () => ({
        data: [
          {
            id: 1,
            name: '北京工人体育场',
            address: '北京市朝阳区工人体育场北路',
            province: {
              id: 1,
              name: '北京市',
              code: '110000'
            },
            city: {
              id: 2,
              name: '北京市',
              code: '110100'
            },
            district: {
              id: 3,
              name: '朝阳区',
              code: '110105'
            },
            latitude: 39.9334,
            longitude: 116.4473,
            isDisabled: 0,
            createdAt: '2024-01-01T00:00:00.000Z',
            updatedAt: '2024-01-01T00:00:00.000Z'
          },
          {
            id: 2,
            name: '北京鸟巢',
            address: '北京市朝阳区国家体育场南路1号',
            province: {
              id: 1,
              name: '北京市',
              code: '110000'
            },
            city: {
              id: 2,
              name: '北京市',
              code: '110100'
            },
            district: {
              id: 3,
              name: '朝阳区',
              code: '110105'
            },
            latitude: 39.9929,
            longitude: 116.3963,
            isDisabled: 0,
            createdAt: '2024-01-01T00:00:00.000Z',
            updatedAt: '2024-01-01T00:00:00.000Z'
          }
        ],
        pagination: {
          current: 1,
          pageSize: 100,
          total: 2
        }
      })
    })
  }
}));

describe('ActivityForm', () => {
  const user = userEvent.setup();
  const mockOnSubmit = vi.fn();
  const mockOnCancel = vi.fn();

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

  it('应该正确渲染创建表单', () => {
    render(
      <TestWrapper>
        <ActivityForm
          onSubmit={mockOnSubmit}
          onCancel={mockOnCancel}
        />
      </TestWrapper>
    );

    expect(screen.getByLabelText('活动名称 *')).toBeInTheDocument();
    expect(screen.getByLabelText('活动类型 *')).toBeInTheDocument();
    expect(screen.getByText('举办地点 *')).toBeInTheDocument();
    expect(screen.getByTestId('venue-location-select')).toBeInTheDocument();
    expect(screen.getByLabelText('开始日期 *')).toBeInTheDocument();
    expect(screen.getByLabelText('结束日期 *')).toBeInTheDocument();
  });

  it('应该正确渲染编辑表单', () => {
    const initialData = {
      id: 1,
      name: '测试活动',
      description: '测试活动描述',
      type: ActivityType.DEPARTURE,
      startDate: new Date('2025-10-17T08:00:00.000Z'),
      endDate: new Date('2025-10-17T18:00:00.000Z'),
      venueLocationId: 1,
      isDisabled: 0
    };

    render(
      <TestWrapper>
        <ActivityForm
          initialData={initialData}
          onSubmit={mockOnSubmit}
          onCancel={mockOnCancel}
        />
      </TestWrapper>
    );

    expect(screen.getByDisplayValue('测试活动')).toBeInTheDocument();
    expect(screen.getByDisplayValue('测试活动描述')).toBeInTheDocument();
    expect(screen.getByDisplayValue('去程活动')).toBeInTheDocument();
  });

  it('应该能够选择举办地点', async () => {
    render(
      <TestWrapper>
        <ActivityForm
          onSubmit={mockOnSubmit}
          onCancel={mockOnCancel}
        />
      </TestWrapper>
    );

    // 点击地点选择器
    const locationSelect = screen.getByTestId('venue-location-select');
    await user.click(locationSelect);

    // 等待地点数据加载
    await waitFor(() => {
      expect(screen.getByText('北京工人体育场')).toBeInTheDocument();
      expect(screen.getByText('北京鸟巢')).toBeInTheDocument();
    });

    // 选择一个地点
    await user.click(screen.getByText('北京工人体育场'));

    // 验证地点被选中
    await waitFor(() => {
      expect(screen.getByText('北京工人体育场')).toBeInTheDocument();
    });
  });

  it('应该验证必填字段', async () => {
    render(
      <TestWrapper>
        <ActivityForm
          onSubmit={mockOnSubmit}
          onCancel={mockOnCancel}
        />
      </TestWrapper>
    );

    // 尝试提交空表单
    await user.click(screen.getByRole('button', { name: '创建活动' }));

    // 验证错误消息
    await waitFor(() => {
      expect(screen.getByText('活动名称不能为空')).toBeInTheDocument();
    });
  });

  it('应该能够提交表单', async () => {
    render(
      <TestWrapper>
        <ActivityForm
          onSubmit={mockOnSubmit}
          onCancel={mockOnCancel}
        />
      </TestWrapper>
    );

    // 填写表单
    await user.type(screen.getByLabelText('活动名称 *'), '测试活动');

    // 选择举办地点
    const locationSelect = screen.getByTestId('venue-location-select');
    await user.click(locationSelect);
    await waitFor(() => {
      expect(screen.getByText('北京工人体育场')).toBeInTheDocument();
    });
    await user.click(screen.getByText('北京工人体育场'));

    // 设置时间
    await user.type(screen.getByLabelText('开始日期 *'), '2025-10-17T08:00');
    await user.type(screen.getByLabelText('结束日期 *'), '2025-10-17T18:00');

    // 提交表单
    await user.click(screen.getByRole('button', { name: '创建活动' }));

    // 验证提交被调用
    await waitFor(() => {
      expect(mockOnSubmit).toHaveBeenCalledWith({
        name: '测试活动',
        description: '',
        type: 'departure',
        startDate: new Date('2025-10-17T08:00:00.000Z'),
        endDate: new Date('2025-10-17T18:00:00.000Z'),
        venueLocationId: 1
      });
    });
  });

  it('应该能够取消表单', async () => {
    render(
      <TestWrapper>
        <ActivityForm
          onSubmit={mockOnSubmit}
          onCancel={mockOnCancel}
        />
      </TestWrapper>
    );

    await user.click(screen.getByRole('button', { name: '取消' }));

    expect(mockOnCancel).toHaveBeenCalled();
  });

  it('应该在编辑模式下显示状态选择', () => {
    const initialData = {
      id: 1,
      name: '测试活动',
      description: '测试活动描述',
      type: ActivityType.DEPARTURE,
      startDate: new Date('2025-10-17T08:00:00.000Z'),
      endDate: new Date('2025-10-17T18:00:00.000Z'),
      venueLocationId: 1,
      isDisabled: 0
    };

    render(
      <TestWrapper>
        <ActivityForm
          initialData={initialData}
          onSubmit={mockOnSubmit}
          onCancel={mockOnCancel}
        />
      </TestWrapper>
    );

    expect(screen.getByLabelText('活动状态')).toBeInTheDocument();
  });
});