/**
 * Tests for ProviderList Component
 * Story 4.4: Provider Switching
 */

import { describe, it, expect, beforeEach, vi } from 'vitest';
import { renderHook, act } from '@testing-library/react';
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import { ProviderList } from './provider-list';
import { useSettingsStore } from '@/store/use-settings';
import type { ProviderProfile } from '@/types/settings';

describe('ProviderList Component', () => {
  beforeEach(() => {
    // Reset store state before each test
    useSettingsStore.getState().actions.clearSettings();
    useSettingsStore.setState({
      providerMigrationState: {
        hasMigrated: false,
      },
      savedProviders: [],
      activeProviderId: null,
    });
  });

  const mockProviders: ProviderProfile[] = [
    {
      id: 'provider-1',
      name: 'OpenAI GPT-4',
      baseUrl: 'https://api.openai.com/v1',
      apiKey: 'sk-openai-key',
      modelName: 'gpt-4o',
      createdAt: '2024-01-24T00:00:00.000Z',
      updatedAt: '2024-01-24T00:00:00.000Z',
    },
    {
      id: 'provider-2',
      name: 'DeepSeek Chat',
      baseUrl: 'https://api.deepseek.com/v1',
      apiKey: 'sk-deepseek-key',
      modelName: 'deepseek-chat',
      createdAt: '2024-01-24T00:00:00.000Z',
      updatedAt: '2024-01-24T00:00:00.000Z',
    },
    ];

  const renderProviderList = (props = {}) => {
    return render(<ProviderList {...props} />);
  };

  describe('rendering', () => {
    it('renders empty state when no providers exist', () => {
      renderProviderList();

      // Should show empty state message
      expect(screen.getByText(/no providers configured/i)).toBeTruthy();
    });

    it('renders all saved providers', () => {
      useSettingsStore.setState({
        savedProviders: mockProviders,
        activeProviderId: 'provider-1',
      });

      renderProviderList();

      expect(screen.getByText('OpenAI GPT-4')).toBeTruthy();
      expect(screen.getByText('DeepSeek Chat')).toBeTruthy();
    });

    it('highlights active provider', () => {
      useSettingsStore.setState({
        savedProviders: mockProviders,
        activeProviderId: 'provider-1',
      });

      renderProviderList();

      const activeProvider = screen.getByText('OpenAI GPT-4').closest('[data-active]');
      expect(activeProvider).toHaveAttribute('data-active', 'true');
    });

    it('shows non-active provider without active highlight', () => {
      useSettingsStore.setState({
        savedProviders: mockProviders,
        activeProviderId: 'provider-1',
      });

      renderProviderList();

      const inactiveProvider = screen.getByText('DeepSeek Chat').closest('[data-active]');
      expect(inactiveProvider).toHaveAttribute('data-active', 'false');
    });
  });

  describe('user interactions', () => {
    it('calls onSelectProvider when provider is clicked', async () => {
      const onSelectProvider = vi.fn();

      useSettingsStore.setState({
        savedProviders: mockProviders,
        activeProviderId: 'provider-1',
      });

      renderProviderList({ onSelectProvider });

      fireEvent.click(screen.getByText('DeepSeek Chat'));

      expect(onSelectProvider).toHaveBeenCalledWith('provider-2');
    });

    it('calls onEditProvider when edit button is clicked', () => {
      const onEditProvider = vi.fn();

      useSettingsStore.setState({
        savedProviders: mockProviders,
        activeProviderId: 'provider-1',
      });

      renderProviderList({ onEditProvider });

      const editButtons = screen.getAllByRole('button', { name: /edit/i });
      expect(editButtons).toHaveLength(2);
    });

    it('calls onDeleteProvider when delete button is clicked', () => {
      const onDeleteProvider = vi.fn();

      useSettingsStore.setState({
        savedProviders: mockProviders,
        activeProviderId: 'provider-1',
      });

      renderProviderList({ onDeleteProvider });

      const deleteButtons = screen.getAllByRole('button', { name: /delete/i });
      expect(deleteButtons).toHaveLength(2);
    });

    it('shows Add New Provider button when provided', () => {
      const onAddProvider = vi.fn();

      renderProviderList({ onAddProvider });

      expect(screen.getByRole('button', { name: /add new provider/i })).toBeTruthy();
    });
  });

  describe('provider information display', () => {
    it('shows provider name as primary label', () => {
      useSettingsStore.setState({
        savedProviders: mockProviders,
        activeProviderId: 'provider-1',
      });

      renderProviderList();

      expect(screen.getByText('OpenAI GPT-4')).toBeTruthy();
    });

    it('shows model name as secondary info', () => {
      useSettingsStore.setState({
        savedProviders: mockProviders,
        activeProviderId: 'provider-1',
      });

      renderProviderList();

      expect(screen.getByText(/gpt-4o/i)).toBeTruthy();
    });
  });

  describe('atomic selectors usage', () => {
    it('uses atomic selectors to prevent re-renders', () => {
      let renderCount = 0;

      const TestWrapper = () => {
        const savedProviders = useSettingsStore((s) => s.savedProviders);
        renderCount++;
        return <ProviderList savedProviders={savedProviders} />;
      };

      render(<TestWrapper />);
      const initialCount = renderCount;

      // Update unrelated state - should not cause re-render of TestWrapper
      act(() => {
        useSettingsStore.getState().actions.setBaseUrl('https://different.com');
      });

      expect(renderCount).toBe(initialCount);
    });
  });
});
