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

describe('AddReminderModal validation', () => {
  const onClose = jest.fn();
  const onAdd = jest.fn();

  beforeEach(() => {
    jest.clearAllMocks();
  });

  it('displays an error when frequency is below the minimum', () => {
    render(<AddReminderModal isOpen onClose={onClose} onAdd={onAdd} />);

    const frequencyInput = screen.getByLabelText('Remind me every (minutes)');
    fireEvent.change(frequencyInput, { target: { value: '1' } });

    expect(
      screen.getByText(/Choose a value between 5 and 720 minutes\./i)
    ).toBeInTheDocument();
    const submitButton = screen.getByRole('button', { name: /add reminder/i });
    expect(submitButton).toBeDisabled();
  });

  it('disables submit when end time is earlier than start time', () => {
    render(<AddReminderModal isOpen onClose={onClose} onAdd={onAdd} />);

    const startInput = screen.getByLabelText('From');
    const endInput = screen.getByLabelText('Until');

    fireEvent.change(startInput, { target: { value: '10:00' } });
    fireEvent.change(endInput, { target: { value: '09:00' } });

    expect(
      screen.getByText(/End time must be later than start time\./i)
    ).toBeInTheDocument();
    expect(
      screen.getByRole('button', { name: /add reminder/i })
    ).toBeDisabled();
  });

  it('calls onAdd with valid data', async () => {
    const resolveAdd = jest.fn().mockResolvedValue(undefined);
    render(<AddReminderModal isOpen onClose={onClose} onAdd={resolveAdd} />);

    fireEvent.change(screen.getByLabelText('Title'), {
      target: { value: 'Hydrate' },
    });
    fireEvent.change(screen.getByLabelText('Remind me every (minutes)'), {
      target: { value: '30' },
    });
    fireEvent.change(screen.getByLabelText('From'), {
      target: { value: '08:00' },
    });
    fireEvent.change(screen.getByLabelText('Until'), {
      target: { value: '12:00' },
    });

    fireEvent.click(screen.getByRole('button', { name: /add reminder/i }));

    await waitFor(() => expect(resolveAdd).toHaveBeenCalledTimes(1));
    expect(resolveAdd).toHaveBeenCalledWith({
      title: 'Hydrate',
      icon: 'bell',
      frequencyMinutes: 30,
      startTime: '08:00',
      endTime: '12:00',
    });
  });
});
