import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { render } from '@testing-library/react'
import { HelmetProvider } from 'react-helmet-async'
import { MemoryRouter } from 'react-router-dom'

import DialogueProvider from '@/components/dialogues/DialogueProvider'
import { KeyboardShortcutsProvider } from '@/lib/useKeyboardShortcuts'
import { UnsavedChangesGuardProvider } from '@/lib/useUnsavedChangesGuard'

import type { ReactElement, ReactNode } from 'react'

type Options = {
  route?: string
}

export const renderWithProviders = (
    ui:       ReactElement,
    options: Options = {},
) => {
  const queryClient = new QueryClient ({
    defaultOptions: {
      queries: { retry: false } },
  })

  const Wrapper = ({ children }: { children: ReactNode }) => (
      <QueryClientProvider client={queryClient}>
        <HelmetProvider>
          <MemoryRouter initialEntries={[options.route ?? '/']}>
            <DialogueProvider>
              <UnsavedChangesGuardProvider>
                <KeyboardShortcutsProvider>
                  {children}
                </KeyboardShortcutsProvider>
              </UnsavedChangesGuardProvider>
            </DialogueProvider>
          </MemoryRouter>
        </HelmetProvider>
      </QueryClientProvider>)

  return {
    queryClient,
    ...render (ui, { wrapper: Wrapper }) }
}
