import { describe, it, expect } from 'vitest';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { MemoryRouter } from 'react-router-dom';
import { AnomalyList } from '../components/AnomalyList';
import type { AnomalySummary } from '../types';

function makeAnomaly(overrides: Partial<AnomalySummary> = {}): AnomalySummary {
  return {
    id: 'anom_1',
    type: 'http_error',
    severity: 'high',
    description: 'HTTP 500 on form submit',
    timestamp: 1000000,
    ...overrides,
  };
}

function renderList(anomalies: AnomalySummary[]) {
  return render(
    <MemoryRouter>
      <AnomalyList anomalies={anomalies} title="Test Anomalies" />
    </MemoryRouter>
  );
}

describe('AnomalyList', () => {
  it('renders title', () => {
    renderList([]);
    expect(screen.getByText('Test Anomalies')).toBeDefined();
  });

  it('shows empty state when no anomalies', () => {
    renderList([]);
    expect(screen.getByText(/no anomalies/i)).toBeDefined();
  });

  it('renders anomaly cards', () => {
    renderList([makeAnomaly(), makeAnomaly({ id: 'anom_2', description: 'Another error' })]);
    expect(screen.getByText('HTTP 500 on form submit')).toBeDefined();
    expect(screen.getByText('Another error')).toBeDefined();
  });

  it('filters by severity when severity button is clicked', async () => {
    const user = userEvent.setup();
    renderList([
      makeAnomaly({ id: 'a1', severity: 'high', description: 'High error' }),
      makeAnomaly({ id: 'a2', severity: 'low', description: 'Low error' }),
    ]);

    // Both are visible initially (all severities selected)
    expect(screen.getByText('High error')).toBeDefined();
    expect(screen.getByText('Low error')).toBeDefined();

    // Click "high" to deselect it
    const highBtn = screen.getAllByRole('button').find((b) => b.textContent === 'HIGH');
    if (highBtn) await user.click(highBtn);

    // High error should now be hidden
    expect(screen.queryByText('High error')).toBeNull();
    expect(screen.getByText('Low error')).toBeDefined();
  });

  it('filters by description search', async () => {
    const user = userEvent.setup();
    renderList([
      makeAnomaly({ id: 'a1', description: 'Server crashed unexpectedly' }),
      makeAnomaly({ id: 'a2', description: 'Timeout on login' }),
    ]);

    const searchInput = screen.getByPlaceholderText(/search/i);
    await user.type(searchInput, 'crashed');

    expect(screen.getByText('Server crashed unexpectedly')).toBeDefined();
    expect(screen.queryByText('Timeout on login')).toBeNull();
  });
});
