import React from 'react';
import { describe, it, expect, vi } from 'vitest';
import { render, screen, waitFor } from '@testing-library/react';

vi.mock('@/api/ai', () => ({
  fetchProviders: vi.fn().mockResolvedValue([
    { id: 'p1', name: 'OpenAI', provider_type: 'openai', api_key: 'sk-***', base_url: '', is_default: true },
    { id: 'p2', name: 'Ollama', provider_type: 'ollama', api_key: '', base_url: 'http://localhost:11434', is_default: false },
  ]),
  createProvider: vi.fn().mockResolvedValue({ id: 'p3' }),
  updateProvider: vi.fn().mockResolvedValue({}),
  deleteProvider: vi.fn().mockResolvedValue({}),
  fetchPresets: vi.fn().mockResolvedValue([
    { id: 'pr1', name: 'GPT-4o', model_id: 'gpt-4o', provider_id: 'p1', temperature: 0.7, max_tokens: 2048, top_p: 1.0, system_prompt: '' },
  ]),
  createPreset: vi.fn().mockResolvedValue({ id: 'pr2' }),
  updatePreset: vi.fn().mockResolvedValue({}),
  deletePreset: vi.fn().mockResolvedValue({}),
  fetchAgents: vi.fn().mockResolvedValue([
    { id: 'a1', name: 'Default Agent', description: 'Default assistant', system_prompt: 'You are helpful', preset_id: 'pr1', tool_ids: ['search'], is_default: true },
  ]),
  createAgent: vi.fn().mockResolvedValue({ id: 'a2' }),
  updateAgent: vi.fn().mockResolvedValue({}),
  deleteAgent: vi.fn().mockResolvedValue({}),
  fetchTools: vi.fn().mockResolvedValue([
    { name: 'search', description: 'Search tool', plugin_name: 'core', category: 'utility', required_permission: null },
  ]),
}));

import { AISettingsPage } from '@/pages/AISettings';

describe('AISettingsPage', () => {
  it('renders AI settings page with title', () => {
    render(<AISettingsPage />);
    expect(screen.getByText('KI Assistent Einstellungen')).toBeInTheDocument();
  });

  it('renders provider tab', () => {
    render(<AISettingsPage />);
    expect(screen.getByText('Anbieter')).toBeInTheDocument();
  });

  it('renders presets tab', () => {
    render(<AISettingsPage />);
    expect(screen.getByText('Modelle & Presets')).toBeInTheDocument();
  });

  it('renders agents tab', () => {
    render(<AISettingsPage />);
    expect(screen.getByText('Agenten')).toBeInTheDocument();
  });

  it('renders tools tab', () => {
    render(<AISettingsPage />);
    expect(screen.getByText('Tools')).toBeInTheDocument();
  });

  it('renders provider list after loading', async () => {
    render(<AISettingsPage />);
    await waitFor(() => {
      expect(screen.getByText('OpenAI')).toBeInTheDocument();
      expect(screen.getByText('Ollama')).toBeInTheDocument();
    });
  });

  it('renders add provider button', async () => {
    render(<AISettingsPage />);
    await waitFor(() => {
      expect(screen.getByText('+ Hinzufügen')).toBeInTheDocument();
    });
  });

  it('renders edit and delete buttons for providers', async () => {
    render(<AISettingsPage />);
    await waitFor(() => {
      expect(screen.getAllByText('Bearbeiten').length).toBeGreaterThan(0);
    });
  });
});
