import React from 'react';
import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { MemoryRouter, Route, Routes } from 'react-router-dom';
import PasswordReset from './PasswordReset';

const mockPost = jest.fn();
const mockExecuteAsync = jest.fn();
const mockReset = jest.fn();

jest.mock('../../components/ParticleBackground/ParticleBackground', () => () => null);

jest.mock('react-google-recaptcha', () => {
  const ReactLib = require('react');
  return ReactLib.forwardRef(
    (
      _props: unknown,
      ref: React.Ref<{ executeAsync: () => Promise<string>; reset: () => void }>
    ) => {
      ReactLib.useImperativeHandle(ref, () => ({
        executeAsync: mockExecuteAsync,
        reset: mockReset,
      }));
      return <div data-testid="recaptcha" />;
    }
  );
});

jest.mock('../../../axiosApi', () => ({
  cleanAxiosInstance: {
    post: (...args: unknown[]) => mockPost(...args),
  },
}));

const renderPasswordReset = () =>
  render(
    <MemoryRouter initialEntries={['/password_reset/']}>
      <Routes>
        <Route path="/password_reset/" element={<PasswordReset />} />
        <Route
          path="/password_reset_confirmation/"
          element={<div>Confirmation page</div>}
        />
      </Routes>
    </MemoryRouter>
  );

describe('PasswordReset', () => {
  beforeEach(() => {
    mockPost.mockReset();
    mockExecuteAsync.mockReset();
    mockReset.mockReset();
    mockExecuteAsync.mockResolvedValue('captcha-token');
    mockPost.mockResolvedValue({ status: 200 });
  });

  it('submits email with captcha token and navigates to confirmation', async () => {
    const user = userEvent.setup();
    renderPasswordReset();

    await user.type(screen.getByPlaceholderText('Email Address'), 'user@example.com');
    await user.click(screen.getByRole('button', { name: 'Reset Password' }));

    await waitFor(() => {
      expect(mockPost).toHaveBeenCalledWith('user/reset_password/', {
        email: 'user@example.com',
        recaptchaToken: 'captcha-token',
      });
    });
    expect(await screen.findByText('Confirmation page')).toBeInTheDocument();
  });

  it('shows error when request fails', async () => {
    mockPost.mockRejectedValue(new Error('network'));
    const user = userEvent.setup();
    renderPasswordReset();

    await user.type(screen.getByPlaceholderText('Email Address'), 'user@example.com');
    await user.click(screen.getByRole('button', { name: 'Reset Password' }));

    expect(
      await screen.findByText('Unable to reset password. Please try again.')
    ).toBeInTheDocument();
    expect(screen.queryByText('Confirmation page')).not.toBeInTheDocument();
  });
});
