import { describe, it, expect, vi } from 'vitest';
import { screen, waitFor } from '@testing-library/react';
import { http, HttpResponse } from 'msw';
import { server } from '../../test/mocks/server';
import { renderWithProviders } from '../../test/utils/renderWithProviders';
import PatientDetail from './PatientDetail';

// Mock useParams to return patient ID
vi.mock('react-router-dom', async () => {
  const actual = await vi.importActual('react-router-dom');
  return {
    ...actual,
    useParams: () => ({ id: 'patient-1' }),
  };
});

// Mock SSE hook
vi.mock('../../hooks/useAlertSSE', () => ({
  useAlertSSE: () => ({ connected: false, connectionState: 'disconnected', recentAlerts: [], reconnect: vi.fn() }),
}));

// Mock useThemeMode
vi.mock('../../hooks/useThemeMode', () => ({
  useThemeMode: () => false,
}));

// Mock AI SSE analysis
vi.mock('../../api/ai/analysisSse', () => ({
  startAnalysis: vi.fn(),
}));

const mockPatient = {
  id: 'patient-1',
  name: '张三',
  gender: 'male',
  birth_date: '1990-01-15',
  blood_type: 'A',
  id_number: '110101199001150001',
  status: 'active',
  verification_status: 'verified',
  source: 'manual',
  allergy_history: '青霉素过敏',
  medical_history_summary: '高血压',
  emergency_contact_name: '李四',
  emergency_contact_phone: '13800000001',
  notes: '定期复查',
  created_at: '2026-04-01T10:00:00Z',
  updated_at: '2026-04-01T10:00:00Z',
  version: 1,
};

function setupPatientDetail(patientId = 'patient-1') {
  server.use(
    http.get(`/api/v1/health/patients/${patientId}`, async () => {
      return HttpResponse.json({ success: true, data: mockPatient });
    }),
  );
}

describe('PatientDetail', () => {
  it('renders patient detail with basic info', async () => {
    vi.setConfig({ testTimeout: 15000 });
    setupPatientDetail();
    renderWithProviders(<PatientDetail />);

    await waitFor(() => {
      expect(screen.getByText('返回列表')).toBeInTheDocument();
    });
    // 张三 appears multiple times (header + description)
    const nameElements = screen.getAllByText('张三');
    expect(nameElements.length).toBeGreaterThanOrEqual(1);
  });

  it('displays patient description fields', async () => {
    setupPatientDetail();
    renderWithProviders(<PatientDetail />);

    await waitFor(() => {
      expect(screen.getByText('青霉素过敏')).toBeInTheDocument();
    });
    expect(screen.getByText('高血压')).toBeInTheDocument();
    expect(screen.getByText('李四')).toBeInTheDocument();
    expect(screen.getByText('13800000001')).toBeInTheDocument();
  });

  it('shows quick navigation links', async () => {
    setupPatientDetail();
    renderWithProviders(<PatientDetail />);

    await waitFor(() => {
      expect(screen.getByText('预约记录')).toBeInTheDocument();
    });
    expect(screen.getByText('咨询记录')).toBeInTheDocument();
    expect(screen.getByText('透析记录')).toBeInTheDocument();
    expect(screen.getByText('随访任务')).toBeInTheDocument();
  });

  it('shows edit button for authorized users', async () => {
    setupPatientDetail();
    renderWithProviders(<PatientDetail />);

    await waitFor(() => {
      expect(screen.getByText('编辑信息')).toBeInTheDocument();
    });
  });

  it('shows tab labels', async () => {
    setupPatientDetail();
    renderWithProviders(<PatientDetail />);

    await waitFor(() => {
      expect(screen.getByText('基本信息')).toBeInTheDocument();
    });
    expect(screen.getByText('家属管理')).toBeInTheDocument();
    expect(screen.getByText('健康数据')).toBeInTheDocument();
    expect(screen.getByText('随访记录')).toBeInTheDocument();
    expect(screen.getByText('积分账户')).toBeInTheDocument();
  });
});
