import { render, RenderOptions } from '@testing-library/react';
import { BrowserRouter, MemoryRouter } from 'react-router-dom';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { LazyToaster } from '@/components/feedback/LazyToaster';
import { ReactElement } from 'react';

/**
 * Test utilities for React components
 * Provides default wrappers with Router, QueryClient, and Toast context
 */

// Create a test QueryClient with default options
const createTestQueryClient = () =>
  new QueryClient({
    defaultOptions: {
      queries: {
        retry: false,
        gcTime: 0,
      },
      mutations: {
        retry: false,
      },
    },
  });

interface AllProvidersProps {
  children: React.ReactNode;
  initialEntries?: string[];
}

const AllProviders = ({ children, initialEntries }: AllProvidersProps) => {
  const queryClient = createTestQueryClient();
  const Router = initialEntries ? MemoryRouter : BrowserRouter;
  const routerProps = initialEntries ? { initialEntries } : {};

  return (
    <Router {...routerProps}>
      <QueryClientProvider client={queryClient}>
        <LazyToaster position="top-right" />
        {children}
      </QueryClientProvider>
    </Router>
  );
};

interface CustomRenderOptions extends Omit<RenderOptions, 'wrapper'> {
  initialEntries?: string[];
}

const customRender = (ui: ReactElement, options?: CustomRenderOptions) => {
  const { initialEntries, ...renderOptions } = options || {};
  return render(ui, {
    wrapper: (props) => (
      <AllProviders {...props} initialEntries={initialEntries} />
    ),
    ...renderOptions,
  });
};

// Re-export everything from @testing-library/react
export * from '@testing-library/react';

// Override render with our custom render
export { customRender as render };

// Export helper for creating test QueryClient
export { createTestQueryClient };
