import React from 'react';
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import ContactModal from '../ContactModal';

function renderModal(onSend: jest.Mock) {
  return render(
    <ContactModal show onHide={jest.fn()} onSend={onSend} recipientName="breizh56" />
  );
}

describe('ContactModal', () => {
  beforeEach(() => {
    jest.clearAllMocks();
  });

  it('shouldNotSendAnEmptyMessage', () => {
    const onSend = jest.fn().mockResolvedValue(undefined);
    renderModal(onSend);

    const sendButton = screen.getByRole('button', { name: 'contact_send' });
    expect(sendButton).toBeDisabled();

    fireEvent.click(sendButton);

    expect(onSend).not.toHaveBeenCalled();
  });

  it('shouldNotSendAWhitespaceOnlyMessageEvenWhenTheFormIsSubmittedDirectly', () => {
    const onSend = jest.fn().mockResolvedValue(undefined);
    renderModal(onSend);

    const textarea = screen.getByRole('textbox');
    fireEvent.change(textarea, { target: { value: '   ' } });
    fireEvent.submit(textarea.closest('form') as HTMLFormElement);

    expect(onSend).not.toHaveBeenCalled();
  });

  it('shouldSendTheTypedMessage', async () => {
    const onSend = jest.fn().mockResolvedValue(undefined);
    renderModal(onSend);

    fireEvent.change(screen.getByRole('textbox'), {
      target: { value: 'Je peux vous emmener depuis Rennes' },
    });
    fireEvent.click(screen.getByRole('button', { name: 'contact_send' }));

    await waitFor(() => {
      expect(onSend).toHaveBeenCalledWith('Je peux vous emmener depuis Rennes');
    });

    expect(await screen.findByText('contact_success')).toBeInTheDocument();
  });
});
