import React from 'react';
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen, waitFor } from '@testing-library/react';
import EventWizardContainer from '@/features/event/containers/EventWizardContainer';
import { renderWithProviders } from '@/test/utils';

// Mock fetchEvents from eventService (keep simple to avoid spread typing issues)
const fetchEventsMock = vi.fn();
vi.mock('@/features/event/api/eventService', () => ({
  fetchEvents: (...args: any[]) => fetchEventsMock(...args),
}));

// Mock useApiFetch to return a passthrough fetch function
vi.mock('@/utils/apiFetch', () => ({
  useApiFetch: () => ((input: RequestInfo, init?: RequestInit) => fetch(input, init)),
}));

// Mock sonner in a hoist-safe way
vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } }));
import { toast } from 'sonner';

// Mock EventWizard presenter to call onReload and render event names
vi.mock('@/features/event/components/EventWizard', () => ({
  default: (props: any) => {
    React.useEffect(() => { props.onReload?.(); }, []);
    return (
      <div>
        {(props.events || []).map((e: any) => (
          <div key={e.id}>{e.name}</div>
        ))}
      </div>
    );
  },
}));

beforeEach(() => {
  vi.restoreAllMocks();
  fetchEventsMock.mockReset();
  (toast.error as any).mockReset?.();
});

describe('EventWizardContainer (integration)', () => {
  it('loads and passes events to presenter', async () => {
    fetchEventsMock.mockResolvedValueOnce([
      { id: 'e1', name: 'Event Eins', begin_date: '2025-01-01', end_date: '2025-01-02' },
    ]);

    const { Wrapper } = renderWithProviders(<div />);
    render(
      <EventWizardContainer onComplete={() => {}} onBackToOverview={() => {}} />, 
      { wrapper: Wrapper as any }
    );

    // Presenter should render the event name once loaded
    const el = await screen.findByText('Event Eins');
    expect(el).toBeTruthy();
  });

  it('handles fetch error and calls toast.error', async () => {
    fetchEventsMock.mockRejectedValueOnce(new Error('Boom'));

    const { Wrapper } = renderWithProviders(<div />);
    render(
      <EventWizardContainer onComplete={() => {}} onBackToOverview={() => {}} />, 
      { wrapper: Wrapper as any }
    );

    await waitFor(() => {
      expect((toast.error as any)).toHaveBeenCalledTimes(1);
    });
  });
});
