import { fireEvent, render } from '@testing-library/react';
import React from 'react';
import { describe, expect, it, vi } from 'vitest';
import { noop } from '../../../../helpers/utils';
import { FreeTextFilter } from './FreeTextFilter';

const sampleText = 'test';
// const filterObj = { $regex: sampleText, $options: 'i' };

describe('FreeTextFilter', () => {
  it('Filter input is rendered', () => {
    const { container } = render(<FreeTextFilter onSelect={noop} />);
    expect(container.querySelector('.inputValue')).toBeInTheDocument();
  });

  it('Entered text on filter should be popped', () => {
    const spy = vi.fn();
    const { container } = render(<FreeTextFilter onSelect={spy} />);
    const input = container.querySelector('.inputValue') as HTMLInputElement;

    fireEvent.keyDown(input, {
      key: 'Enter',
      target: { value: sampleText },
    });
    expect(spy).toHaveBeenCalledWith(sampleText);
  });

  it('Executes validator and displays message', () => {
    const spy = vi.fn();
    const { container } = render(
      <FreeTextFilter onSelect={spy} onValidate={() => 'invalid'} />,
    );
    const input = container.querySelector('.inputValue') as HTMLInputElement;

    fireEvent.keyDown(input, {
      key: 'Enter',
      target: { value: sampleText },
    });

    expect(spy).toHaveBeenCalledTimes(0);

    const error = container.querySelector('small');

    expect(error).toBeDefined();
  });

  it('selects text on focus when selectOnFocus is true and there is a value', () => {
    vi.useFakeTimers();
    const mockValue = 'test value';
    const spy = vi.fn();

    const { container } = render(
      <FreeTextFilter onSelect={spy} value={mockValue} selectOnFocus={true} />,
    );
    const input = container.querySelector('input') as HTMLInputElement;
    fireEvent.focus(input);

    // Fast-forward until all timers have been executed
    vi.runAllTimers();

    expect(input.selectionStart).toBe(0);
    expect(input.selectionEnd).toBe(mockValue.length);
  });
});
