import { render } from '@testing-library/react';
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { BrowserRouter, MemoryRouter } from 'react-router-dom';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { ProtectedRoute } from './ProtectedRoute';

// Mock useAuthStore
const mockIsAuthenticated = vi.fn(() => false);

vi.mock('@/features/auth/store/authStore', () => ({
  useAuthStore: () => ({
    isAuthenticated: mockIsAuthenticated(),
  }),
}));

const createTestQueryClient = () =>
  new QueryClient({
    defaultOptions: {
      queries: { retry: false },
      mutations: { retry: false },
    },
  });

const TestWrapper = ({ children }: { children: React.ReactNode }) => {
  const queryClient = createTestQueryClient();
  return (
    <QueryClientProvider client={queryClient}>
      <BrowserRouter>{children}</BrowserRouter>
    </QueryClientProvider>
  );
};

describe('ProtectedRoute Component', () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it('renders children when user is authenticated', () => {
    mockIsAuthenticated.mockReturnValue(true);

    const { getByText } = render(
      <TestWrapper>
        <ProtectedRoute>
          <div>Protected Content</div>
        </ProtectedRoute>
      </TestWrapper>,
    );

    expect(getByText('Protected Content')).toBeInTheDocument();
  });

  it('redirects to login when user is not authenticated', () => {
    mockIsAuthenticated.mockReturnValue(false);

    render(
      <MemoryRouter initialEntries={['/dashboard']}>
        <QueryClientProvider client={createTestQueryClient()}>
          <ProtectedRoute>
            <div>Protected Content</div>
          </ProtectedRoute>
        </QueryClientProvider>
      </MemoryRouter>,
    );

    // Le composant Navigate devrait rediriger vers /login
    // On vérifie que le contenu protégé n'est pas visible
    const protectedContent = document.querySelector('div');
    expect(protectedContent?.textContent).not.toBe('Protected Content');
  });

  it('uses replace navigation when redirecting', () => {
    mockIsAuthenticated.mockReturnValue(false);

    const { container } = render(
      <MemoryRouter initialEntries={['/dashboard']}>
        <QueryClientProvider client={createTestQueryClient()}>
          <ProtectedRoute>
            <div>Protected Content</div>
          </ProtectedRoute>
        </QueryClientProvider>
      </MemoryRouter>,
    );

    // Le composant Navigate devrait être présent avec replace
    expect(container).toBeInTheDocument();
  });

  it('renders multiple children correctly when authenticated', () => {
    mockIsAuthenticated.mockReturnValue(true);

    const { getByText } = render(
      <TestWrapper>
        <ProtectedRoute>
          <div>Child 1</div>
          <div>Child 2</div>
        </ProtectedRoute>
      </TestWrapper>,
    );

    expect(getByText('Child 1')).toBeInTheDocument();
    expect(getByText('Child 2')).toBeInTheDocument();
  });

  it('handles empty children gracefully', () => {
    mockIsAuthenticated.mockReturnValue(true);

    const { container } = render(
      <TestWrapper>
        <ProtectedRoute>{null}</ProtectedRoute>
      </TestWrapper>,
    );

    expect(container).toBeInTheDocument();
  });
});
