import React from 'react';
import { fireEvent } from '@testing-library/react-native';
import { render } from '@/components/testUtils';
import NumberSelector, { NumberSelectorProps } from '@/components/shared/NumberSelector';

const renderComponent = ({ reps = 5, setReps = jest.fn() }: NumberSelectorProps) => {
  const base = render(
    <NumberSelector reps={reps} setReps={setReps} />
  );

  return base;
};

describe('[Component] NumberSelect', () => {
  test('renders correctly', () => {
    const component = renderComponent({ reps: 5, setReps: jest.fn() });

    expect(component).toMatchSnapshot();
  });

  test('renders the correct initial reps value', () => {
    const { getByText } = renderComponent({ reps: 5, setReps: jest.fn() });

    expect(getByText('5')).toBeTruthy();
  });

  test('increments reps when "+" is pressed', () => {
    const setRepsMock = jest.fn();
    const { getByText } = renderComponent({ reps: 5, setReps: setRepsMock });

    fireEvent.press(getByText('+'));

    expect(setRepsMock).toHaveBeenCalledWith(6);
  });

  test('decrements reps when "-" is pressed', () => {
    const setRepsMock = jest.fn();
    const { getByText } = renderComponent({ reps: 5, setReps: setRepsMock });

    fireEvent.press(getByText('-'));

    expect(setRepsMock).toHaveBeenCalledWith(4);
  });

  test('does not decrement reps below 0', () => {
    const setRepsMock = jest.fn();
    const { getByText } = renderComponent({ reps: 0, setReps: setRepsMock });

    fireEvent.press(getByText('-'));

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

  test('displays the reps correctly after increment and decrement', () => {
    let repsValue = 5;
    const setRepsMock = jest.fn((newReps) => {
      repsValue = newReps;
    });

    const { getByText, rerender } = renderComponent({ reps: repsValue, setReps: setRepsMock });

    fireEvent.press(getByText('+'));
    rerender(<NumberSelector reps={repsValue} setReps={setRepsMock} />);

    expect(getByText('6')).toBeTruthy();

    fireEvent.press(getByText('-'));
    rerender(<NumberSelector reps={repsValue} setReps={setRepsMock} />);

    expect(getByText('5')).toBeTruthy();
  });
});
