import React from 'react';
import { render, screen, fireEvent } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import DesireForm from './DesireForm';

describe('DesireForm', () => {
  test('renders desire submission form with all input fields and submit button', () => {
    render(<DesireForm onSubmit={() => {}} />);
    
    // Check for headings/labels for each category
    expect(screen.getByText(/What You Want/i)).toBeInTheDocument();
    expect(screen.getByText(/Afraid to Ask \(Private\)/i)).toBeInTheDocument();
    expect(screen.getByText(/What You Accept/i)).toBeInTheDocument();
    expect(screen.getByText(/What You Do Not Want/i)).toBeInTheDocument();

    // Check for the submit button
    const submitButton = screen.getByRole('button', { name: /Submit Desires/i });
    expect(submitButton).toBeInTheDocument();
  });

  test('submits correct data including afraidToAsk field', async () => {
    const handleSubmit = jest.fn();
    render(<DesireForm onSubmit={handleSubmit} />);

    const wantsInput = screen.getByLabelText(/Enter items you want/i);
    const acceptsInput = screen.getByLabelText(/Enter items you accept/i);
    const noGoesInput = screen.getByLabelText(/Enter items you absolutely do not want/i);
    const afraidToAskInput = screen.getByLabelText(/Enter sensitive ideas privately/i);
    const submitButton = screen.getByRole('button', { name: /Submit Desires/i });

    await userEvent.type(wantsInput, 'More vacation');
    await userEvent.type(acceptsInput, 'Flexible hours');
    await userEvent.type(noGoesInput, 'Mandatory overtime');
    await userEvent.type(afraidToAskInput, 'A raise');

    fireEvent.click(submitButton);

    expect(handleSubmit).toHaveBeenCalledWith({
      wants: ['More vacation'],
      accepts: ['Flexible hours'],
      noGoes: ['Mandatory overtime'],
      afraidToAsk: 'A raise',
    });
  });

  test('shows alert if no desires are entered, including afraidToAsk', async () => {
    const handleSubmit = jest.fn();
    render(<DesireForm onSubmit={handleSubmit} />);
    const submitButton = screen.getByRole('button', { name: /Submit Desires/i });

    const alertMock = jest.spyOn(window, 'alert').mockImplementation(() => {});

    fireEvent.click(submitButton);

    expect(alertMock).toHaveBeenCalledWith('Please enter at least one desire in any category.');
    expect(handleSubmit).not.toHaveBeenCalled();

    alertMock.mockRestore();
  });
});
